为什么Perl的Try :: Tiny的try / catch没有给我与eval相同的结果?

时间:2010-05-20 07:03:43

标签: perl eval try-catch

为什么使用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"

1 个答案:

答案 0 :(得分:12)

你错过了try / catch块的最后一个分号。

你有:

try  {
    ...
}
catch {
    ...
}
return;

因此,您拥有的代码相当于:try( CODEREF, catch( CODEREF, return ) );

<强>更新

我忘了提及,修改代码只需更改shell_command_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;
}