为什么 Perl 的 Try::Tiny 的 try/catch 没有给我与 eval 相同的结果?
为什么带有 try/catch 的子例程没有给出与 eval-version 相同的结果?
#!/usr/bin/env perl
use warnings; use strict;
use 5.012;
use Try::Tiny;
sub shell_command_1 {
my $command = shift;
my $timeout_alarm = shift;
my @array;
eval {
local $SIG{ALRM} = sub { die "timeout '$command'\n" };
alarm $timeout_alarm;
@array = qx( $command );
alarm 0;
};
die $@ if $@ && $@ ne "timeout '$command'\n";
warn $@ if $@ && $@ eq "timeout '$command'\n";
return @array;
}
shell_command_1( 'sleep 4', 3 );
say "Test_1";
sub shell_command_2 {
my $command = shift;
my $timeout_alarm = shift;
my @array;
try {
local $SIG{ALRM} = sub { die "timeout '$command'\n" };
alarm $timeout_alarm;
@array = qx( $command );
alarm 0;
}
catch {
die $_ if $_ ne "timeout '$command'\n";
warn $_ if $_ eq "timeout '$command'\n";
}
return @array;
}
shell_command_2( 'sleep 4', 3 );
say "Test_2"
Why doesn't the subroutine with try/catch give me the same results as the eval-version does?
#!/usr/bin/env perl
use warnings; use strict;
use 5.012;
use Try::Tiny;
sub shell_command_1 {
my $command = shift;
my $timeout_alarm = shift;
my @array;
eval {
local $SIG{ALRM} = sub { die "timeout '$command'\n" };
alarm $timeout_alarm;
@array = qx( $command );
alarm 0;
};
die $@ if $@ && $@ ne "timeout '$command'\n";
warn $@ if $@ && $@ eq "timeout '$command'\n";
return @array;
}
shell_command_1( 'sleep 4', 3 );
say "Test_1";
sub shell_command_2 {
my $command = shift;
my $timeout_alarm = shift;
my @array;
try {
local $SIG{ALRM} = sub { die "timeout '$command'\n" };
alarm $timeout_alarm;
@array = qx( $command );
alarm 0;
}
catch {
die $_ if $_ ne "timeout '$command'\n";
warn $_ if $_ eq "timeout '$command'\n";
}
return @array;
}
shell_command_2( 'sleep 4', 3 );
say "Test_2"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您缺少 try/catch 块上的最后一个分号。
您有:
所以,您的代码相当于:
try( CODEREF, catch( CODEREF, return ) );
更新:
我忘了提及,修复您的代码只需更改
shell_command_2
:You are missing the final semicolon on the try/catch blocks.
You have:
So, you have code that is equivalent to:
try( CODEREF, catch( CODEREF, return ) );
Update:
I forgot to mention, to fix your code simply change
shell_command_2
: