perl - "no warnings;"在安全隔间

标签 perl warnings eval

我正在使用 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/

相关文章:

windows - perl if( -e "带空格路径的窗口){}

perl - 通过仅加载模块的一部分来节省资源?

java - 如何从 Excel (.xlsb) 二进制文件格式中读取数据?

c++ - C/C++ 编译器警告 : do you clean up all your code to remove them or leave them in?

javascript - 将字符串转换为模板字符串

linux - 替换括号中的单词以放入引号中

c - 错误: Wrong comparison between pointer and integer

latex - 我如何将 LaTeX 警告视为错误

php - 如何在php中动态设置数组键

javascript - 获取嵌套的对象值