Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you get Perl to stop when referencing an undef value?

How do you get Perl to stop and give a stack trace when you reference an undef value, rather than merely warning? It seems that use strict; isn't sufficient for this purpose.

like image 930
Neil Avatar asked Sep 16 '08 22:09

Neil


4 Answers

use warnings FATAL => 'uninitialized';

use Carp ();
$SIG{__DIE__} = \&Carp::confess;

The first line makes the warning fatal. The next two cause a stack trace when your program dies.

See also man 3pm warnings for more details.

like image 169
cjm Avatar answered Oct 31 '22 18:10

cjm


Instead of the messy fiddling with %SIG proposed by everyone else, just use Carp::Always and be done.

Note that you can inject modules into a script without source modifications simply by running it with perl -MCarp::Always; furthermore, you can set the PERL5OPT environment variable to -MCarp::Always to have it loaded without even changing the invocation of the script. (See perldoc perlrun.)

like image 41
Aristotle Pagaltzis Avatar answered Oct 31 '22 17:10

Aristotle Pagaltzis


Include this:

use Carp ();

Then include one of these lines at the top of your source file:

local $SIG{__WARN__} = \&Carp::confess;
local $SIG{__WARN__} = \&Carp::cluck;

The confess line will give a stack trace, and the cluck line is much more terse.

like image 4
Neil Avatar answered Oct 31 '22 17:10

Neil


One way to make those warnings fatal is to install a signal handler for the WARN virtual-signal:

$SIG{__WARN__} = sub { die "Undef value: @_" if $_[0] =~ /undefined/ };
like image 2
zigdon Avatar answered Oct 31 '22 17:10

zigdon