yic
yic

Reputation: 720

Perl exit on warning

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

How can one do this?

Upvotes: 6

Views: 884

Answers (3)

mob
mob

Reputation: 118595

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: @_";        
};

Upvotes: 2

melpomene
melpomene

Reputation: 85757

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

Upvotes: 4

toolic
toolic

Reputation: 62019

The warnings pragma has the FATAL option:

use warnings FATAL => 'all';

Upvotes: 6

Related Questions