如果生成警告,我怎样才能使Perl死掉?

时间:2020-12-28 21:04:43

I would like my script perl to die whenever a warning is generated, including warnings which are generated by used packages.

我希望我的脚本perl在生成警告时死亡,包括由使用过的包生成的警告。

For example, this should die:

例如,这应该死:

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'; won't help since it's lexically scoped. Test::NoWarnings also doesn't do the work since it doesn't kill the script.

使用警告FATAL =>'all';不会有帮助,因为它是词汇范围的。测试:: NoWarnings也不起作用,因为它不会杀死脚本。

2 个解决方案

#1


9  

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:

要添加到rafl的答案:在向%SIG添加处理程序时,(通常)最好不要覆盖任何以前的处理程序,但在执行代码后调用它:

my $old_warn_handler = $SIG{__WARN__};
$SIG{__WARN__} = sub {

    # DO YOUR WORST...

    $old_warn_handler->(@_) if $old_warn_handler;
};

(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.)

(这也适用于信号处理程序,如$ SIG {HUP},$ SIG {USR1}等。您永远不知道是否有其他软件包(甚至是“你”的另一个实例)已经设置了仍需要运行的处理程序。 )

#2


16  

I believe you're looking for $SIG{__WARN__} as documented in perlvar. Something similar to

我相信你正在寻找perlvar中记录的$ SIG {__ WARN__}。类似的东西

$SIG{__WARN__} = sub { die @_ };

might be what you want.

可能是你想要的。

#1


9  

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:

要添加到rafl的答案:在向%SIG添加处理程序时,(通常)最好不要覆盖任何以前的处理程序,但在执行代码后调用它:

my $old_warn_handler = $SIG{__WARN__};
$SIG{__WARN__} = sub {

    # DO YOUR WORST...

    $old_warn_handler->(@_) if $old_warn_handler;
};

(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.)

(这也适用于信号处理程序,如$ SIG {HUP},$ SIG {USR1}等。您永远不知道是否有其他软件包(甚至是“你”的另一个实例)已经设置了仍需要运行的处理程序。 )

#2


16  

I believe you're looking for $SIG{__WARN__} as documented in perlvar. Something similar to

我相信你正在寻找perlvar中记录的$ SIG {__ WARN__}。类似的东西

$SIG{__WARN__} = sub { die @_ };

might be what you want.

可能是你想要的。