Set exit status if perl -cw issues a warning

I would like perl -cw ... to return a non-zero exit status if a compilation warning is issued.

eg. suppose this a.pmis a file:

use warnings;
asd;

Then perl -cw a.pmreports:

Unquoted string "asd" may clash ...
Useless use of a constant in void context ...
a.pm syntax OK

and the exit status is set to 0. I would like to be able to detect that compilation warnings have been issued - preferably if I set the exit status.

+5
source share
3 answers

Install the warning handler in the block BEGIN(near the top of the script, so that this block is parsed before the code, which may cause warnings at compile time) and sets the exit status to . END CHECK

use strict;
use warnings;
my $warnings;
BEGIN {
    $SIG{__WARN__} = sub { $warnings++; CORE::warn @_ }
}
$used::only::once = 42;
CHECK {
    if ($^C && $warnings > 0) {
        exit $warnings;
    }
}

$^C , perl -c.

+7

, . , ( ) . , , , .

$ perl -M'warnings FATAL=>q(all)' -cw a.pm ; echo $?
Unquoted string "asd" may clash with future reserved word at a.pm line 2.
255
+5

$SIG{__WARN__}, . :

package warncounter;

use strict;
use warnings;

my $warnings;

BEGIN {
    $SIG{__WARN__} = sub {
        $warnings++;
        CORE::warn(@_);
        exit(255);
    };
}

1;

perl -Mwarncounter -wc test.pl

perl . , END, -c END.

+2

All Articles