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

后端 未结 2 641
我寻月下人不归
我寻月下人不归 2021-02-19 21:30

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:



        
相关标签:
2条回答
  • 2021-02-19 22:06

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

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

    might be what you want.

    0 讨论(0)
  • 2021-02-19 22:08

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

    0 讨论(0)
提交回复
热议问题