debugging intermediate

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 help
  • n - Execute next line (step over)
  • s - Step into subroutines
  • c - Continue until breakpoint or end
  • p $var - Print variable value
  • x @array - Dump array/hash contents
  • b 10 - Set breakpoint at line 10
  • L - List breakpoints
  • q - 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 n to begin
  • Variable interpolation in print statements may hide bugs; use x to see actual structure
  • Lexical variables (my) are only visible in their scope when debugging
  • Use V to 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

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
Starting calculation...
Running total: 1
Running total: 5
Running total: 14
Running total: 30
Running total: 55
Final result: 55
STDERR
(empty)

Was this helpful?

Related Questions