为什么Perl的Try :: Tiny的try/catch不给我与eval相同的结果? [英] Why doesn't Perl's Try::Tiny's try/catch give me the same results as eval?

查看:137
本文介绍了为什么Perl的Try :: Tiny的try/catch不给我与eval相同的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么带有try/catch的子例程不能给我与eval-version相同的结果?

Why doesn't the subroutine with try/catch give me the same results as the eval-version does?

#!/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块上缺少最后一个分号.

You are missing the final semicolon on the try/catch blocks.

您有:

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

因此,您具有的代码等效于:try( CODEREF, catch( CODEREF, return ) );

So, you have code that is equivalent to: try( CODEREF, catch( CODEREF, return ) );

更新:

我忘了提,要解决您的代码,只需更改shell_command_2:

I forgot to mention, to fix your code simply change 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;
}

这篇关于为什么Perl的Try :: Tiny的try/catch不给我与eval相同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆