Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set exit status if perl -cw emits warning

Tags:

perl

I'd like perl -cw ... to return a non-zero exit status if a compilation warning is emitted.

E.g. suppose a.pm is the file:

use warnings;
asd;

Then perl -cw a.pm reports:

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'd like to be able to detect that compilation warnings were emitted - preferably though setting of the exit status.

like image 569
ErikR Avatar asked Nov 07 '11 15:11

ErikR


2 Answers

Set a warning handler in a BEGIN block (near the top of the script, so this block is parsed before the code that might trigger compile-time warnings), and tweak the exit status in an ENDCHECK block.

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

The $^C variable is true if and only if you have invoked perl with the -c option.

like image 71
mob Avatar answered Sep 27 '22 19:09

mob


As far as I know, this isn't possible. After all, they are only advisory notices not strictly (no pun intended) errors. Inversely, however, you can promote warnings to fatal errors at runtime if that helps to address your objective.

$ 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
like image 20
JRFerguson Avatar answered Sep 27 '22 19:09

JRFerguson