Debugging and Profiling

48.1 Debugging Techniques

use Data::Dumper; local $Data::Dumper::Sortkeys = 1; warn Dumper($data);
use Data::Printer; p $data;                           # colorized
use Carp::Always;                                     # stack traces on every die/warn (perl -MCarp::Always script.pl)
use diagnostics;                                      # verbose warning explanations
warn "DEBUG: value=[$value]\n" if $ENV{DEBUG};        # quick debug output with brackets to spot whitespace

48.2 The Perl Debugger

l / v / . List code / view around the line / return to the current line n / s / r

Next (step over) / step into / return from the sub Continue (to a line) b line [cond] / b subname

Set a breakpoint (optionally conditional) Delete all breakpoints / list breakpoints p expr / x expr Print / dump a data structure Watch an expression

Show lexical variables (requires PadWalker) Editors: VS Code (Perl Navigator + Perl::LanguageServer debugging), Komodo IDE, Padre. Devel::ptkdb (Tk GUI debugger), Devel::hdb (browser-based debugger).

perl -d script.pl
perl -de0                         # interactive REPL

48.3 Profiling

perl -d:NYTProf script.pl         # Devel::NYTProf: the best Perl profiler
nytprofhtml --open                # HTML report: time per line/sub, call graphs, flame graphs
use Benchmark qw(cmpthese timethese);
cmpthese(-2, {                    # run each for 2 CPU seconds
    concat => sub { my $s = ''; $s .= 'x' for 1..1000 },
    join   => sub { my $s = join '', ('x') x 1000 },
});
use Devel::Size qw(total_size); say total_size(\%big_hash);   # memory usage
use Devel::Peek; Dump($scalar);   # internal SV structure
use Test::LeakTrace;              # find memory leaks
use Devel::Cycle; find_cycle($obj);   # find circular references