1

需要运行外部命令,将输出写入日志文件并捕获退出状态

my $cmd = "db2 \"insert into schema.tablea (id, name, city) values (99, 'Micheal', 'London')\" ";
open my $log, ">", "logfile.log";
my $rt = open(OUTPUT,"$cmd 2>&1 | " );
while (<OUTPUT>){
   chomp;
   print $log $_, "\n";
   print $_, "\n";
}
close(OUTPUT);
close($log);
print "Exit status is $rt\n";

任何帮助都将不胜感激。

4

2 回答 2

1

close因为这种句柄将按$?原样设置system

die $! if $? == -1;
die "Killed by ".( $? & 0x7F ) if $? & 0x7F;
die "Exited with ".( $? >> 8 ) if $? >> 8;

如果你无论如何都要掏钱,你不妨考虑

use String::ShellQuote qw( shell_quote );
system("$cmd 2>&1 | tee ".shell_quote($log));
于 2013-03-27T22:15:19.870 回答
0

你可以使用 Capture::Tiny:

    use Capture::Tiny ':all';
    use File::Slurp;
    use autodie;

    ($stdout, $stderr, $exit) = tee sub {
        system("echo hello; exit 15");
    };

    write_file('logfile.log', $stdout);
    print "exit: ", $exit >> 8, "\n";

“$exit >> 8”的解释见“perldoc -f system”。

于 2013-03-28T09:02:36.727 回答