为什么';t Perl';s Try::Tiny';s try/catch能给我和eval一样的结果吗?

为什么';t Perl';s Try::Tiny';s try/catch能给我和eval一样的结果吗?,perl,eval,try-catch,Perl,Eval,Try Catch,为什么try/catch的子例程不能给出与eval版本相同的结果 #!/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 "ti

为什么try/catch的子例程不能给出与eval版本相同的结果

#!/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"

try/catch块上缺少最后一个分号

你有:

try  {
    ...
}
catch {
    ...
}
return;
因此,您的代码相当于:
try(CODEREF,catch(CODEREF,return))

更新:

我忘了提到,要修复代码,只需更改
shell\u命令\u 2

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";
    };           # <----- Added ; here <======= <======= <======= <=======
    return @array;
}
子shell命令\u 2{
我的$command=shift;
my$timeout\u alarm=shift;
我的@数组;
试一试{
本地$SIG{ALRM}=sub{die“timeout'$command'\n};
报警$timeout\u报警;
@array=qx($command);
报警0;
}
抓住{
如果$\uNE“超时”$命令“\n”;
警告$\if$\uEQ“超时”$命令“\n”;

}##记住要包括你得到的结果。