Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

kimmel's scratchpad

by kimmel (Beadle)
on Jun 19, 2011 at 18:12 UTC ( #910460=scratchpad: print w/ replies, xml ) Need Help??

working title: Debugging: Inspecting a variable as the value changes

This is a simple tutorial on how to find out when a variable's value changes without needing prior knowledge of the codebase.

It is common practice when writing/debugging/refactoring/messing around with a program that you want to know when a certain variable is set or its value changes. For example I was looking at this piece code
if ( $show_banner == 1 ) { print STDERR "$app_name $version ($app_www)\n"; print STDERR "$copyright $author, $author_email\n\n"; }
and I realized it was never getting executed. I could have just sprinkled in some print $show_banner; statements but this code was written by another programmer so I am not familiar with its structure and flow so I would waste time learning the code to know the best places to put a print statement.

There has to be a faster way to track this variable and I know this is a pretty common problem. So what is the Perl answer you ask? CPAN. There I found the Tie::Trace module.

Tie::Trace allows you to watch a variable and every time the value changes you get a debug message. Here is how I added it to my existing program.

use Tie::Trace qw( watch ); my $show_banner = 1; watch $show_banner;
Then I ran my application and got the following output.
main:: $show_banner => 0 at ./colordiff.pl line 156.
From there I ran the test suite to see if $show_banner changed due to any edge cases. Each test in the test suite produced the same above output.

Now I knew where the value was being changed. From there it was a simple change to an if statement and a rerun of the application test suite to verify no regressions were introduced.

The watch function provided by Tie::Trace does all the heavy lifting by issuing print Dumper statements on the variable as it changes. This is an invaluable tool for following value changes of variables as a program executes.

Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (7)
As of 2014-07-23 01:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (131 votes), past polls