2010-05-20 17 views
5

Pourquoi la sous-routine avec try/catch ne me donne-t-elle pas les mêmes résultats que la version eval?Pourquoi Try/Tiny de Perl's try/catch ne me donne pas les mêmes résultats que 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 [email protected] if [email protected] && [email protected] ne "timeout '$command'\n"; 
    warn [email protected] if [email protected] && [email protected] 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" 
+0

N'oubliez pas d'inclure le résultat que vous obtenez. –

Répondre

12

Il vous manque le point-virgule final sur les blocs try/catch.

Vous avez:

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

Donc, vous avez du code qui est équivalent à: try(CODEREF, catch(CODEREF, return));

Mise à jour:

j'oublié de mentionner, pour corriger votre code simplement changer 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; 
}