How to debug Perl script with perl -d?
Question
How to debug Perl script with perl -d?
The Perl debugger is invoked using the -d flag with the perl command: perl -d script.pl. This launches an interactive debugging session where you can step through code, examine variables, set breakpoints, and trace execution flow.
Basic Debugger Commands
Once in the debugger, you'll see a DB<1> prompt. Essential commands include:
h- Display helpn- Execute next line (step over)s- Step into subroutinesc- Continue until breakpoint or endp $var- Print variable valuex @array- Dump array/hash contentsb 10- Set breakpoint at line 10L- List breakpointsq- Quit debugger
Runnable Example
Here's a script demonstrating common debugging scenarios. Save it and run with perl -d script.pl:
#!/usr/bin/perl
use strict;
use warnings;
# This script demonstrates debugger-friendly code
my $total = 0;
my @numbers = (1, 2, 3, 4, 5);
print "Starting calculation...\n";
foreach my $num (@numbers) {
$total += calculate_square($num);
print "Running total: $total\n";
}
print "Final result: $total\n";
sub calculate_square {
my ($n) = @_;
my $result = $n * $n;
return $result;
}
# When run normally (without -d), this prints:
# Starting calculation...
# Running total: 1
# Running total: 5
# Running total: 14
# Running total: 30
# Running total: 55
# Final result: 55
One-Liner Debugging
You can debug one-liners using perl -d -e 'code'. For quick variable inspection without full interactive mode, use -d:Trace to print each line as it executes.
Common Gotchas
- The debugger stops before executing the first line, so use
nto begin - Variable interpolation in print statements may hide bugs; use
xto see actual structure - Lexical variables (
my) are only visible in their scope when debugging - Use
Vto display all variables in the current package
For Perl 5.12+, you can also use perl -d:ptkdb for a graphical debugger interface if the Devel::ptkdb module is installed, though the standard debugger is always available in core Perl.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 19ms
Starting calculation...
Running total: 1
Running total: 5
Running total: 14
Running total: 30
Running total: 55
Final result: 55
(empty)