2010-05-20 4 views
5

try/catch를 사용하는 서브 루틴이 eval-version과 동일한 결과를 얻지 못하는 이유는 무엇입니까?Perl의 Try :: Tiny의 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 [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

당신이 얻은 결과를 포함시키는 것을 잊지 마십시오. –

답변

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; 
} 
관련 문제