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

is the right way to trap uninitialized reference by wrapping an eval around the entire program? or is there a way to tell perl to call my sub when it encounters an uninitialized variable, which would otherwise trigger a warnings (or FATAL exception if set)? thanks, perl wizards...
  • Comment on use warnings uninitialized to my own sub?

Replies are listed 'Best First'.
Re: use warnings uninitialized to my own sub?
by perl_lover (Chaplain) on Dec 08, 2010 at 06:50 UTC
    You can write your handler for $SIG{__WARN__}
    local $SIG{__WARN__} = sub { die $_[0] };



    use Perl;
    Perl4Everything
      works like a charm:
      #!/usr/bin/perl -w use strict; #use warnings FATAL => qw{ uninitialized }; local $SIG{__WARN__} = sub { die "your variable is not defined!\n"; }; my $var; print "the variable is $var\n";
      thank you.
        Do realize that the warnings handle does not discriminate against the warning. If it installed, it will be called for every warning - be it from an uninitialized variable or something else. (Note that uninitialized variable is a bit of a misnomer, the trigger is an undefined value (not an undefined variable). Undefined values may happen because no value was every assigned to the variable, but it may also be an undefined value was assigned to it).