gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 03:19:02 26 4
gpt4 key购买 nike

为什么带有 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"

最佳答案

您缺少 try/catch block 上的最后一个分号。

你有:

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

关于perl - 为什么 Perl 的 Try::Tiny 的 try/catch 没有给出与 eval 相同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2871619/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com