在 Perl 中有三種方式來(lái)調(diào)用外部程序。
system()
?返回程序的退出狀態(tài)my $rc = system("/bin/cp $file1 $file2"); # returns exit status values
die "system() failed with status $rc" unless $rc == 0;
如果可能,用列表傳遞你的參數(shù),而不是用單個(gè)的字符串。
my $rc = system("/bin/cp", $file1, $file2 );
如果?$file1
?或?$file2
?有空格或其他特殊字符,這將確保不會(huì)在 Shell 中出錯(cuò)。
system()
?的輸出不會(huì)被捕獲。
qx()
?操作符返回程序的輸出當(dāng)你想要輸出時(shí),使用:
my $output = `myprogram foo bar`;
你將需要檢查?$!
?中的錯(cuò)誤代碼。
如果你使用反引號(hào)或?qx()
,首選?IPC::Open2?或?IPC::Open3?代替,因?yàn)?它們將給你相同的參數(shù)控制,并允許你捕獲輸出。
IPC::Open3
?是在 Perl 中不使用 Shell 命令來(lái)捕獲?STDERR
?的僅有方法。
更多建議: