kdubs kdubs - 3 days ago 6
Perl Question

using perl how can you figure out how to turn off a specific warning

I've got some legacy code that I'm dealing with. It's too much to clean up in one shot. It's using \1 inside of the s operator. I looked into perllexwarn and found I can shut it off with 'no warnings qw(syntax)', but I did this with trial and error. Is there an easier way to get right from the warning to the way to shut it off?

It's doing stuff like this:

use strict;
$_ = "abc";
s/abc/\1/;
no warnings qw(syntax);
s/abc/\1/;


the message it generates is :

\1 better written as $1

Answer

Execute your script as

perl -Mdiagnostics ./a.pl

or temporarily add use diagnostics; to your script. This will produce something like

\1 better written as $1 at ./a.pl line 4 (#1)
    (W syntax) Outside of patterns, backreferences live on as variables.
    The use of backslashes is grandfathered on the right-hand side of a
    substitution, but stylistically it's better to use the variable form
    because other Perl programmers will expect it, and it works better if
    there are more than 9 backreferences.

Notice the (W syntax)? The letter is one of the following, and the word is the warning class for which you are looking.

  • (W) A warning (optional).
  • (D) A deprecation (enabled by default).
  • (S) A severe warning (enabled by default).
  • (F) A fatal error (trappable).
  • (P) An internal error you should never see (trappable).
  • (X) A very fatal error (nontrappable).
  • (A) An alien error message (not generated by Perl).

diagnostics gets its information from perldiag, which you could search manually instead of using use diagnostics;.


Other examples:

$ perl -Mdiagnostics -we'print undef'
Use of uninitialized value in print at -e line 1 (#1)
    (W uninitialized) An undefined value was used as if it were already
    [...]

$ perl -Mdiagnostics -we'no warnings qw( uninitialized ); print undef'

$ perl -Mdiagnostics -we'sub foo { } sub foo { }'
Subroutine foo redefined at -e line 1 (#1)
    (W redefine) You redefined a subroutine.  To suppress this warning, say
    [...]

$ perl -Mdiagnostics -we'no warnings qw( redefine ); sub foo { } sub foo { }'

$
Comments