Perl:成功的系统调用后,“或死".命令仍然结束脚本 [英] Perl: After a successful system call, "or die" command still ends script

查看:219
本文介绍了Perl:成功的系统调用后,“或死".命令仍然结束脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下行进行有效的简单系统调用:

I am using the following line to make a simple system call which works:

system ("mkdir -p Purged") or die "Failed to mkdir." ;

执行脚本确实可以进行系统调用,我可以找到一个名为Purged的目录,但是错误消息仍然会打印出来,并且脚本消失.我的语法有什么问题?

Executing the script does make the system call and I can find a directory called Purged, but the error message is still printed and the script dies. What is wrong with my syntax?

推荐答案

那会有些混乱,不是吗? -莱昂纳多·埃雷拉(Leonardo Herrera)在池上的答案

是的,system命令在Perl中颠倒了true和false,并创建了如下有趣的逻辑,这令人困惑:

Yes, it is confusing that the system command inverts true and false in Perl, and creates fun logic like this:

if ( system qw($command) ) {
    die qq(Aw... If failed);
}
else {
    say qq(Hooray! It worked!);
}

但是,system命令执行此操作的原因是可以理解的.在Unix中,退出状态为零表示程序正常运行,而非零状态可以为您提供system调用失败原因的信息.也许您正在调用的程序不存在.也许程序按预期工作了.例如,grep工作时grep返回退出代码1,但是没有匹配的行.您可能想区分grep何时返回零,一或返回码大于一. (是的,我知道在Perl程序中使用系统调用grep是很愚蠢的,但这是我想到的第一个示例.)

But, it's understandable why the system command does this. In Unix, an exit status of zero means the program worked, and a non-zero status could give you information why your system call failed. Maybe the program you were calling doesn't exist. Maybe the program sort of worked as expected. For example, grep returns an exit code of 1 when grep works, but there were no matching lines. You might want to distinguish when grep returns zero, one, or a return code greater than one. (Yes, I know it's silly to use a system call to grep in a Perl program, but that's the first example I could think of).

为了防止偶然的混乱,我创建了一个变量来保存我的system命令的退出状态,而不是直接测试system的输出:

To prevent casual confusion, I create a variable that holds the exit status of my system command instead of testing the output of system directly:

my $error = system qw($command);
if ($error) {
    die qq(Aw... It failed);
}
else {
    say qq(Hooray! It worked!);
}

这完全没有必要,使用Perl的人应该知道system颠倒了Perl对 true false 的定义,但是如果我没有喝咖啡的话早上,当我浏览别人的代码时,我可能会想念它.做这一小步只会使程序看起来更具逻辑性.

It's completely unnecessary, and people who work with Perl should know that system reverses Perl's definition of true and false, but if I hadn't had my coffee in the morning, I may miss it as I go over someone else's code. Doing this little step just makes the program look a bit more logical.

系统的Perldoc为您提供了可以测试您的输出的代码系统命令以查看发生了什么. (如果出现错误,或者系统中断信号终止了system调用).很高兴知道您是否需要查询您的system返回值以找出问题所在.

The Perldoc of system give you code that allows you to test the output of your system command to see exactly what happened. (If there was an error, or a system interrupt signal killed the system call). It's nice to know if you need to interrogate your system return value to figure out what went wrong.

这篇关于Perl:成功的系统调用后,“或死".命令仍然结束脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆