Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Due to my own syntax bug, what essentially happened was ...

cat p.pl; echo ; perl -Dr p.pl printf "matched: %s\n" , ( 'x' =~ undef() ? 'yes' : 'no' ) ; Omitting $` $& $' support. EXECUTING... Compiling REx "" Final program: 1: NOTHING (2) 2: END (0) minlen 0 Matching REx "" against "x" 0 <> <x> | 1:NOTHING(2) 0 <> <x> | 2:END(0) Match successful! matched: yes Freeing REx: ""

Is there a way to turn a *match attempt against an undef variable* to be deadly at run time? (I am well aware of the warning generated when matching against an undef value. By that warning itself I had located the error of my ways.)

Replies are listed 'Best First'.
Re: Turn matching against undef to be deadly
by vsespb (Chaplain) on Sep 26, 2013 at 13:16 UTC
    use strict; use warnings; use Carp; local $SIG{__WARN__} = sub { if ($_[0] =~ /Use of uninitialized value in regexp compilation/) { confess $_[0]; } else { warn @_; } }; print "x".undef, "\n"; printf "matched: %s\n" , ( 'x' =~ undef() ? 'yes' : 'no' ) ; __END__ Use of uninitialized value in concatenation (.) or string at 1.pl line + 14. x Use of uninitialized value in regexp compilation at 1.pl line 16. at 1.pl line 7. main::__ANON__('Use of uninitialized value in regexp compilati +on at 1.pl line...') called at 1.pl line 16


    pros: it works.

    cons:
    1. I think you should at least unit-test it, because warning format can change in different perl versions.
    2. Dynamic scoped (this can be worked around with %^H, probably)

      Thanks, vsespb.

      The likelihood of change in warning and having to match against a string are the reasons why I forgot to mention about WARN signal as soon as I had thought about it before posting.

        As another Anonymous Monk pointed above you can use warnings 'FATAIL' for all warnings or only "uninitialized". Lexical scope used. But this will catch other types of "uninitialized" warnings.
        use strict; use warnings; use Carp; use warnings FATAL => 'uninitialized'; printf "matched: %s\n" , ( 'x' =~ undef() ? 'yes' : 'no' ) ; print "end\n";