Debugging Perl Scripts

(Up-to-date source of this post.)

When there's a problem while writing a Perl program the thing I do often is to print out the contents of a variable. There are two ways I usually do it.

If the the variable is not complex (i.e. it's a simple scalar, array or hash variable) I use the print function:
use strict;
use warnings;

# A number between 1 and 100 (both included)
my $secret = int( 1 + rand 100 );

# If DEBUG environment variable set, print out the secret number
print "The secret number is $secret"
    if $ENV{DEBUG};
Then I just set the environment variable while running the script:
$ DEBUG=1 ./script.pl
The secret number is 3
In case I'm dealing with a more complicated data structure, like the $server variable below, I use Data::Dumper (which outputs valid Perl code):
use strict;
use warnings;
use Data::Dumper;

my $name = 'foo';

my $server = {
    'server' => {
        'imageRef'  => '8a3a9f96-b997-46fd-b7a8-a9e740796ffd',
        'flavorRef' => '2',
        'name'      => $name,
        'metadata'  => { 'My Server Name' => 'Ubuntu 12.10 (Quantal Quetzal)' },

print Dumper $server;

The Perl Debugger

Sometimes I need something more than just printing out the variable contents. In that case I reach for the Perl debugger:
$ perl -d prog.pl
It shows each line of code before it executes it. The most common commands are these:
  • h -- help
  • s -- single-step the program
  • x -- dump a variable value (for complex data use x \%href or even x sort keys %hash)
  • n -- step over a subroutine
  • q -- quit the debugger
To have the command line history within the Perl debugger, you need to install:
  • Debian/Ubuntu packages: libncurses-dev libreadline-dev
  • Perl module: Term::ReadLine::Gnu


No comments:

Post a Comment