How can I make Perl die if a warning is generated?

半城伤御伤魂 提交于 2019-12-21 07:30:55

问题


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

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.


回答1:


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;
};

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




回答2:


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

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

might be what you want.



来源:https://stackoverflow.com/questions/3896060/how-can-i-make-perl-die-if-a-warning-is-generated

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!