Tie Perl variables for debugging

If you suspect a variable like %ENV is being altered somewhere without your knowing about it, put

BEGIN{use Tie::Trace;Tie::Trace::watch %ENV}
at the top of your script (before you use any other modules). Then you'll get a warning message every time an environment variable changes in your Perl script. This uses the Perl Tie::Trace module.

Here is an example. The following test script calls a module called Goon:

#!/usr/local/bin/perl
use warnings;
use strict;
BEGIN{use Tie::Trace;Tie::Trace::watch %ENV}
use Goon;
$ENV{FLAB} = 1;
But Goon.pm is misbehaving by setting the environment variable "YADA":
package Goon;

$ENV{YADA} = 1;

1;
The script prints out the following:
$ ./test.pl 
{YADA} => 1 at Goon.pm line 3.
{FLAB} => 1 at ./test.pl line 6.

This idea comes from this "Stackoverflow.com" answer and its comment.
Copyright © Ben Bullock 2009-2010. All rights reserved. For comments, questions, and corrections, please email Ben Bullock/ Privacy/ Disclaimer