Page-6(Back 2 Basics)

How to Debug a PERL Program :

There are multiple ways to debug a Perl program, few of them are as follows:

1. You should run your code with the -w command line option, or with

use warnings;

specified at the top of your code. Both of these operations cause Perl to check at both compile and run time that you're not specifying something that's technically invalid, but unlikely to be what you intended - it'll pick you up on uninitialized variables, variable names that only occur once, bare words that should probably have a $ in front of them, and so on.

2. The humble print statement can be very revealing - add in a few extra output statements for intermediate variables and you'll soon start to see where about in your code its behavior starts to deviate from what you had intended.

3. The Data::Dumper module allows you to "pretty print" data structures if you want to go beyond the print statement - perhaps you have whole lists or hashes that you want to dump out? (Link - source example using Data::Dumper)

#!/usr/bin/perl

use Sys::Hostname;

use Cwd;

use Getopt::Std;

use File::Find;

use File::Compare;

use English;

use Data::Dumper;

use Benchmark;

(getopts('vd:') and @ARGV == 1)

or die ("Usage $PROGRAM_NAME [-v] [-d directory] filename\n");

$dir = $opt_d || ".";

print ("Running on ",hostname()," from ",getcwd(),"\n") if ($opt_v) ;

timethese (1, {'perlcode' => sub {

find (sub {push @got,$File::Find::name if /$ARGV[0]/},$dir);

@got or push @got,"nothing!";

print Dumper(\@got) if ($opt_v);

print ("Looked for $ARGV[0] in $dir and found\n",join ("\n",@got),"\n");

$f = shift @got;

foreach $file(@got) {

compare($f,$file) and print "WARNING - $file differs from $f\n";

}

}});

4. Perl comes with an interactive debugger - run Perl with the -d option if you want to run this way. There's a tutorial on this in the perl distribution - run perldoc perldebtut at the command line for more details. [Note:- This is the most important debugger available in Perl, run the command and read the documentation/examples]

5. There's various CPAN modules to help you too - ptkdb and Devel::ebug provide a GUI to help debug, and programatic hooks for you to add your own debug facilities, if that's what you want.

And finally, there are commercial debuggers such as ActiveState's Komodo.

External Links:

1. http://www.wellho.net/

2. http://www.wellho.net/mouth/743_How-to-debug-a-Perl-program.html