1.使用system函数调用
代码如下:
@args = ("command", "arg1", "arg2");
system(@args) == 0
or die "system @args failed: $?"System将使用perl预定义的特殊变量$?捕获程序执行的返回值--即所执行程序的退出状态。用户若想得到实际的程序退出代码,还需要右移8位,或者除以256。
You can check all the failure possibilities by inspecting $? like this:
用户可以通过使用$?对程序执行失败的原因进行分析。代码如下:
if ($? == -1) {
print "failed to execute: $!\n";
}
elsif ($? & 127) {
printf "child died with signal %d, %s coredump\n",
($? & 127), ($? & 128) ? 'with' : 'without';
}
else {
printf "child exited with value %d\n", $? >> 8;
}更多信息,可参考“perldoc -f system ”或者web:http://perldoc.perl.org/functions/system.html
2.使用`命令行`方式执行
使用这种方式,perl将返回程序执行过程中所有的output。
To capture a command's STDERR and STDOUT together:
同时获取命令的STDERR和STDOUT:
$output = `cmd 2>&1`;
To capture a command's STDOUT but discard its STDERR:
仅获取命令的STDOUT,忽略STDERR:
$output = `cmd 2>/dev/null`;
仅获取命令的STDERR,忽略STDOUT:
$output = `cmd 2>&1 1>/dev/null`;更多信息,可参考web: