我正在使用 reval来自 Perl 的 Safe如果无法解析正在评估的字符串,我想阻止它生成警告(实际上,我想阻止它生成任何警告)。
例如,下面的代码:
use strict; use warnings;
use Safe;
use feature qw/say/;
my $cft = Safe->new;
my $x = $cft->reval(') 1' );
my $y = $cft->reval('2' );
say "x: $x";
say "y: $y";
结果是:
Number found where operator expected at (eval 5) line 1, near ") 1"
(Missing operator before 1?)
Use of uninitialized value $x in concatenation (.) or string at ./test line 12.
x:
y: 2
我想要实现的是让 $x = undef 和 $y = 2,并且没有警告。
我试图提出“没有警告;”在新范围内,但它对 reval 内产生的警告没有影响(尽管正如@DavidO 所指出的,它使“未初始化值”警告静音):
use strict; use warnings;
use Safe;
use feature qw/say/;
my $cft = Safe->new;
{
no warnings;
my $x = $cft->reval(') 1' );
my $y = $cft->reval('2' );
say "x: $x";
say "y: $y";
}
我想不知何故,“无警告”必须在保险箱内,所以我也尝试在“无警告”前面加上“无警告”;到被评估的字符串:
use strict; use warnings;
use Safe;
use feature qw/say/;
my $cft = Safe->new;
{
my $x = $cft->reval( 'no warnings;' . ') 1' );
my $y = $cft->reval( 'no warnings;' . '2' );
say "x: $x";
say "y: $y";
}
这样 reval 不会发出任何警告,但两个变量都是 undef:
Use of uninitialized value $x in concatenation (.) or string at ./test line 10.
x:
Use of uninitialized value $y in concatenation (.) or string at ./test line 11.
y:
我不知道还有什么可以尝试的,我希望问题描述足够清楚。
最佳答案
如果您查看 $@
你会看到 $cft->reval( 'no warnings;' . ') 1' );
失败的。 'require' trapped by operation mask at (eval 5) line 1.
.换句话说,Safe 正在完成它的工作并阻止该代码尝试加载库。$cft->reval( 'BEGIN { warnings->unimport; } ) 1' );
会起作用,假设警告已经加载到隔间外。但是,这不会消除编译时错误。不像 eval
, reval
似乎让他们通过。使用 amon 的静默 STDERR 技术。
关于perl - "no warnings;"在安全隔间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11677576/