如果生成警告,如何使Perl死掉?
我希望我的脚本perl在生成警告(包括用过的软件包所生成的警告)时死掉.
I would like my script perl to die whenever a warning is generated, including warnings which are generated by used packages.
例如,这应该死:
use strict;
use warnings;
use Statistics::Descriptive;
my @data = ( 8, 9, 10, "bbb" );
my $stat = Statistics::Descriptive::Full->new();
$stat->add_data(@data);
use warnings FATAL => 'all';
将无济于事,因为它在词法范围内. Test :: NoWarnings 也不起作用,因为它不会杀死脚本.
use warnings FATAL => 'all';
won't help since it's lexically scoped. Test::NoWarnings also doesn't do the work since it doesn't kill the script.
要添加到rafl的答案:在向%SIG
添加处理程序时,(通常)最好不要覆盖以前的任何处理程序,而是在执行后调用它您的代码:
To add to rafl's answer: when adding a handler to %SIG
, it is (usually) better to not overwrite any previous handler, but call it after performing your code:
my $old_warn_handler = $SIG{__WARN__};
$SIG{__WARN__} = sub {
# DO YOUR WORST...
$old_warn_handler->(@_) if $old_warn_handler;
};
(这也适用于信号处理程序,例如$SIG{HUP}
,$SIG{USR1}
等.您
永远不知道是否有其他软件包(甚至是您"的另一个实例)
设置仍需要运行的处理程序.)
(This also applies to signal handlers like $SIG{HUP}
, $SIG{USR1}
, etc. You
never know if some other package (or even another instance of "you") already
set up a handler that still needs to run.)