在 PHP 中你可以使用 @
在函数调用之前抑制返回的警告。
Perl 中有类似的东西吗?
最佳答案
PHP 的这个特性很疯狂,应该尽可能避免。
Perl 有两种异常: fatal error 和警告。警告可能由 Perl 本身发出,也可能由用户代码发出。
在某个静态/词法范围内,Perl 的内置警告可以像这样关闭:
use warnings;
foo();
sub foo {
no warnings 'uninitialized'; # recommended: only switch of specific categories
warn "hello\n";
1 + undef; # Otherwise: Use of uninitialized value in addition (+)
}
输出:
hello
在 STDERR 上。(可以找到所有警告类别的列表 here )
但这不能用于从您正在调用的代码中删除警告(动态范围)。这也不会使用户定义的警告静音。
在这种情况下,您可以为
__WARN__
编写处理程序。伪信号:use warnings;
{
local $SIG{__WARN__} = sub { };
foo();
print "bye\n";
}
sub foo {
warn "hello\n";
1 + undef;
}
输出:
bye
在标准输出上。我们可以把它抽象成一个函数
muffle
:sub muffle {
my $func = shift;
local $SIG{__WARN__} = sub { };
return $func->(@_);
}
muffle(\&foo, 1, 2, 3); # foo(1, 2, 3)
然而,这是一件非常愚蠢的事情:
undef
value 字符串化为空字符串,并且不想要任何警告。 此处概述的策略不处理致命异常,请使用
Try::Tiny
反而。
关于perl - 如何抑制来自 Perl 函数的警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19490351/