我目前正在修改一个执行多个shell命令的Perl脚本,并且对于其中的一些命令,捕获输出以供进一步处理。我想分解在子例程中执行外部命令的代码。我写了下面的子程序:从子线程执行外部命令(并读取其输出)
sub execute_command {
my $cmd = shift;
Log("executing command $cmd ...");
system($cmd);
my $app = ($? == -1) ? $? : $? >> 8;
if ($app != 0) {
Log("error executing command $cmd");
return $FAILURE;
}
Log("done");
return $SUCCESS;
}
sub execute_command_and_get_output {
my $cmd = shift;
Log("executing command $cmd ...");
unless (open(CMD, "$cmd|")) {
Log("error executing command $cmd");
return undef;
}
my @cmd = <CMD>;
close(CMD);
Log("done");
return @cmd;
}
问题:
execute_command
应该在错误的情况下执行该命令传递和返回$SUCCESS
如果一切正常,或$FAILURE
。我是否正确测试$?
?execute_command_and_get_output
应执行传递的命令并将输出作为数组返回(包含输出行);如果命令的执行失败,则应返回undef
。使用unless (open(CMD, "$cmd|")) { ... }
来测试命令执行中的错误条件是否正确?
除了我的两个问题的答案,任何改善建议表示赞赏。
感谢您的回答:我很欣赏的想法,但是我更喜欢从'execute_command_and_get_output'返回多个值,我也不行多使用反引号的。 – MarcoS