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

2

13

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.

Dipteran answered 9/10, 2010 at 15:4 Comment(0)
K
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:

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

Kisung answered 9/10, 2010 at 18:44 Comment(1)
This is the better approach... Just like C, the signals need to cooperate and cascade or you will have unintended actions at a distance modifying global handlers with a single value.Driskill
P
19

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

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

might be what you want.

Pinite answered 9/10, 2010 at 15:9 Comment(1)
But note that you're changing a global and might see unintended consequences. It would probably be a good idea to audit the packages you use for modifications to $SIG{__WARN__}.Briquette
K
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:

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

Kisung answered 9/10, 2010 at 18:44 Comment(1)
This is the better approach... Just like C, the signals need to cooperate and cascade or you will have unintended actions at a distance modifying global handlers with a single value.Driskill

© 2022 - 2024 — McMap. All rights reserved.