为什么Perl 6的尝试不处理shell()中的非零退出? [英] Why doesn't Perl 6's try handle a non-zero exit in shell()?
问题描述
此 try 捕获到异常:
try die X::AdHoc;
say "Got to the end";
输出显示程序继续:
Got to the end
如果我尝试使用 shell
和一个不以0退出的命令,则尝试无法捕获它:
If I attempt it with shell
and a command that doesn't exit with 0, the try doesn't catch it:
try shell('/usr/bin/false');
say "Got to the end";
输出看起来不是异常:
The spawned command '/usr/bin/false' exited unsuccessfully (exit code: 1)
in block <unit> at ... line ...
这到底是怎么回事?
推荐答案
答案确实由乔纳森·沃辛顿(Jonathan Worthington)提供:
The answer is really provided by Jonathan Worthington:
https://irclog.perlgeek.de/perl6-dev/2017-04-04#i_14372945
简而言之,shell()返回一个Proc对象.该对象下沉的那一刻,如果运行程序失败,它将引发内部异常.
In short, shell() returns a Proc object. The moment that object is sunk, it will throw the exception that it has internally if running the program failed.
$ 6 'dd shell("/usr/bin/false")'
Proc.new(in => IO::Pipe, out => IO::Pipe, err => IO::Pipe, exitcode => 1, signal => 0, command => ["/usr/bin/false"])
因此,您需要做的是将Proc对象捕获到变量中,以防止其沉没:
So, what you need to do is catch the Proc object in a variable, to prevent it from being sunk:
$ 6 'my $result = shell("/usr/bin/false"); say "Got to the end"'
Got to the end
然后您可以使用$ result.exitcode来查看它是否成功.
And then you can use $result.exitcode to see whether it was successful or not.
这篇关于为什么Perl 6的尝试不处理shell()中的非零退出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!