2010-05-20 10 views
5

कोशिश/पकड़ के साथ सबराउटिन क्यों न ही मुझे परिणाम देता है जैसे eval-version करता है?पर्ल की कोशिश क्यों नहीं करें :: छोटे की कोशिश/पकड़ मुझे वही परिणाम देता है जैसे 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] && $@ 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

आपको जो परिणाम मिल रहा है उसे शामिल करना याद रखें। –

उत्तर

12

आप कोशिश/पकड़ ब्लॉक पर अंतिम अर्धविराम गायब हैं।

आपके पास:

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; 
}