2013-03-27 38 views
1

需要運行和外部命令,輸出寫入任何幫助apreciated一個日誌文件,並捕獲退出狀態的Perl - 捕獲退出狀態和捕獲記錄最好的辦法對外部命令

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"; 

+1

您可能想看看IPC :: Run或IPC :: Open3 – kjprice 2013-03-27 21:29:32

+0

任何原因,特別是您爲什麼不想使用DBI和DBD :: DB2? – 2013-03-29 14:42:08

回答

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)); 
0

你可以使用捕捉::微型:

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"; 

請參閱「perldoc -f系統「用於解釋」$ exit >> 8「。