Why doesn't Perl 6's try handle a non-zero exit in shell()?

心已入冬 提交于 2021-02-08 13:24:11

问题


This try catches the exception:

try die X::AdHoc;
say "Got to the end";

The output shows that the program continues:

 Got to the end

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 output doesn't look like an exception:

The spawned command '/usr/bin/false' exited unsuccessfully (exit code: 1)
  in block <unit> at ... line ...

What's going on that this makes it through the try?


回答1:


The answer is really provided by Jonathan Worthington:

https://irclog.perlgeek.de/perl6-dev/2017-04-04#i_14372945

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"])

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

And then you can use $result.exitcode to see whether it was successful or not.



来源:https://stackoverflow.com/questions/43199427/why-doesnt-perl-6s-try-handle-a-non-zero-exit-in-shell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!