perl eval“...传播”记录在哪里

where is perl eval "...propagated" documented

在下面的代码中,eval 检查表达式是否有效。 它捕获了一个异常,我的代码打印出异常,而代码并没有在那时死掉。到目前为止,还不错。

但是当随后遇到 die; 表达式时,异常文本会再次 打印出来 ,没有我的要求,添加了 ...propagated 消息,给出 die; 命令的行号。 但在这一点上,异常文本是不合适的和令人困惑的。 似乎 perl 保留 eval 错误消息或异常消息,直到我们到达 die;.

在下面发布的代码下方有两个解决方法,其中任何一个都可以使该行为消失。

在哪里记录了这种特殊行为?背后的想法是什么?

#!/usr/bin/perl
use strict; use warnings;
my $str=q/(d/;
my $rgx;
eval{$rgx=qr/$str/};
if(length $@)
{
   print join('', 'qr/', $str, '/ does not compile: ',"\n", $@, );
}
print "Got past eval. But next, at 'die;', it will print an error message that no longer pertains.\n";
die;

解决方法 (1)。给 die; 一个非空字符串:

#!/usr/bin/perl
use strict; use warnings;
my $str=q/(d/;
my $rgx;
eval{$rgx=qr/$str/};
if(length $@)
{
   print join('', 'qr/', $str, '/ does not compile: ',"\n", $@, );
}
print "Got past eval. Next, the nonempty string in die ' '; flushes out the inappropriate exception message.\n";
die ' ';

解决方法 (2)。执行另一个 eval 没有发现语法错误:

#!/usr/bin/perl
use strict; use warnings;
my $str=q/(d/;
my $rgx;
eval{$rgx=qr/$str/};
if(length $@)
{
    print join('', 'qr/', $str, '/ does not compile: ',"\n", $@, );
}
print "got past eval\n";
$str=0;
eval{$rgx=qr/$str/};
die;

这是相当合乎逻辑的行为,我会说,die 没有参数使用。它应该做什么?

记录在 die

If LIST was empty or made an empty string, and $@ already contains an exception value (typically from a previous eval), then that value is reused after appending "\t...propagated". This is useful for propagating exceptions:

eval { ... };
die unless $@ =~ /Expected exception/;

[...]

因此,发出不带任何参数的不相关 die 会在该设施中混淆。

您需要向 die 提供错误消息。如果您不这样做,这就是可能的 documented 结果之一。

If LIST was empty or made an empty string, and $@ already contains an exception value (typically from a previous eval), then that value is reused after appending "\t...propagated". This is useful for propagating exceptions:

eval { ... };
die unless $@ =~ /Expected exception/;

如果你想退出而不打印任何东西,你需要exit

exit( $! || ( $? >> 8 ) || 255 );   # The value that `die` uses.

但是,以下是更好且更惯用的解决方案:

my $rgx = eval { qr/$str/ }
   or die("Can't compile qr/$str/: $@");