例如,我正在尝试执行系统命令
system('git clone .....' );
if ($?) {
croak('Error while cloning git repository');
}
在这里,我检查结果是否成功,但如何不从系统命令输出错误,例如在我的情况下,我可以得到类似的东西
Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
执行命令。
我需要把这个错误放到变量中并抑制它(不要把它打印到终端)
然后检查此错误消息。
或者至少是压制它。
我需要用下面的方法测试这样的子程序
dies_ok { MyModule::sub_uses_system_command() } 'Died :(';
有可能得到这样的结果吗?
Thx提前
4条答案
按热度按时间uajslkp61#
system
只返回执行的程序的退出状态,如果你想得到标准输出,你可以使用qx/command/
或反引号来执行命令:您应该注意,
qx/command/
和反引号形式的执行命令只返回STDOUT,因此如果您想捕获STDERR,则需要在命令中将STDERR重定向到STDOUT。2nc8po8w2#
使用
qx
而不是system
来捕获命令的输出。看起来你还想捕获stderr,所以使用标准的2>&1
来dup stderr on to stdout。o2rvlv0m3#
如果你需要做多个输出到STDERR/STDOUT的测试,你可以在一个块中重定向它们,并在其中运行所有这些测试。
omvjsjqw4#
您可以重定向输出:
如果命令是动态构建的(需要参数),
system()
可以说比qx//
更好,因为你不需要参与插值和引用。你可以将参数传递给shell,并在-c
的参数中使用它们作为shell变量: