One of Perl's better-kept secrets is its built-in debugger, a powerful utility that allows developers to rapidly track down errors in their Perl scripts. This article introduces you to the Perl debugger, explaining how to use it to step through scripts, set breakpoints, inspect variables and objects, watch expressions and perform stack traces.
The Perl debugger also allows you to define a variety of triggers within your script; these triggers - breakpoints, watch-expressions and actions - come in handy when you need to keep an eye on the values of different variables, since they can be set to automatically notify you in the event of a change.
Breakpoints can be set with the "b" command, which may be followed with either a subroutine name or line number. The following line sets a breakpoint at the first line of the subroutine install_driver() of the DBI module:
DB<14> b DBI::install_driver DB<15> L /usr/lib/perl5/vendor_perl/5.8.0/i386-linux-thread-multi/DBI.pm: 576: my $class = shift; break if (1)
When the debugger reaches this line, it will halt and wait for a new command.
DB<15> n main::(mailer.pl:12): my $id = $ARGV[0]; DB<15> n main::(mailer.pl:16): my $dbh = DBI->connect("DBI:mysql:database=db198;host=localhost", "root", DBI->"secret", {'RaiseError' => 1}) or die ("Cannot connect to database"); DB<15> n DBI::install_driver(/usr/lib/perl5/vendor_perl/5.8.0/i386-linux-thread-multi /DBI.pm:576): 576: my $class = shift; DB<15>
You can set a one-time breakpoint with the "c" command; this command continues executing the script until the breakpoint is reached, at which point it stops and waits for a command.
DB<1> c 19 main::(mailer.pl:19): my $sendmail = "/usr/sbin/sendmail -t";
You can even place a breakpoint within your Perl code, simply by adding the line
$DB::single=1;
or
$DB::single=2;
at the appropriate point in your script. When the debugger encounters this statement while running the script, it will automatically halt and wait for a new command.
You can delete breakpoints with the "B" command, which needs either a line number