Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl exit on warning

I'd like a perl script to exit with error code immediately on any kind of warning. For example, on an "argument ... isn't numeric in addition" warning.

How can one do this? Thank you in advance.

like image 488
yic Avatar asked Mar 25 '17 17:03

yic


3 Answers

The warnings pragma has the FATAL option:

use warnings FATAL => 'all';
like image 129
toolic Avatar answered Nov 18 '22 02:11

toolic


toolic's answer of use warnings FATAL => 'all'; is correct, but there are some caveats. There are some warnings emitted by internal perl functions that really don't expect to be dying. There's a list of those unsafe-to-fatalize warnings in perldoc strictures.

As of version 2.000003 of strictures, it enables warnings as follows:

use warnings FATAL => 'all';
use warnings NONFATAL => qw(
  exec
  recursion
  internal
  malloc
  newline
  experimental
  deprecated
  portable
);
no warnings 'once';

See https://metacpan.org/pod/strictures#CATEGORY-SELECTIONS for the full rationale.

Instead of copy/pasting the above lines into your code, you could of course just

use strictures 2;

which also enables strict for you. (You might have to install strictures first, though.)

like image 21
melpomene Avatar answered Nov 18 '22 01:11

melpomene


Not mentioned yet, but you can set a __WARN__ handler and do what you like there.

$SIG{__WARN__} = sub {
    die "This program does not tolerate warnings like: @_";        
};
like image 1
mob Avatar answered Nov 18 '22 03:11

mob