PERLDEBUG(1perl)
π NAME π
perldebug β Perl debugging π
(yes bestie, this is the "Perl Programmers Reference Guide" one, perldebug(1perl))
β¨ DESCRIPTION β¨
Okay so first of all, before literally anything else: have you tried using use strict; and use warnings;? π«Ά Fr. Start there.
If you're new to the Perl debugger, you may prefer to read perldebtut, which is a tutorial introduction to the debugger.
If you're looking for the nitty gritty details of how the debugger is implemented, you may prefer to read perldebguts.
For in-depth technical usage details, see perl5db.pl, the documentation of the debugger itself.
π¦ The Perl Debugger π¦
If you invoke Perl with the -d switch, your script runs under the Perl source debugger. It's giving interactive Perl environment, no cap β it prompts you for debugger commands that let you examine source code, set breakpoints, get stack backtraces, change the values of variables, etc. This is so convenient that you often fire up the debugger all by itself just to test out Perl constructs interactively to see what they do. For example:
$ perl -d -e 42
In Perl, the debugger is not a separate program the way it usually is in the typical compiled environment. Instead, the -d flag tells the compiler to insert source information into the parse trees it's about to hand off to the interpreter. Which means your code must first compile correctly for the debugger to work on it. Then when the interpreter starts up, it preloads a special Perl library file containing the debugger.
The program will halt right before the first run-time executable statement (but see below regarding compile-time statements) and ask you to enter a debugger command. And contrary to popular expectations, whenever the debugger halts and shows you a line of code, it always displays the line it's about to execute, rather than the one it has just executed. π
Any command not recognized by the debugger is directly executed (eval'd) as Perl code in the current package. (The debugger uses the DB package for keeping its own state information.)
Note that the said eval is bound by an implicit scope. As a result any newly introduced lexical variable or any modified capture buffer content is lost after the eval. The debugger is a nice environment to learn Perl, but if you interactively experiment using material which should be in the same scope, stuff it in one line. π
For any text entered at the debugger prompt, leading and trailing whitespace is first stripped before further processing. If a debugger command coincides with some function in your own program, merely precede the function with something that doesn't look like a debugger command, such as a leading ; or perhaps a +, or by wrapping it with parentheses or braces.
πΈ Calling the Debugger πΈ
There are several ways to call the debugger:
perl -d program_nameβ on the given program identified by program_name.perl -d -e 0β interactively supply an arbitrary expression using-e.perl -d:ptkdb program_nameβ debug a given program via the Devel::ptkdb GUI.perl -dt threaded_program_nameβ debug a given program using threads (experimental).
If Perl is called with the -d switch, the variable $^P will hold a true value. This is useful if you need to know if your code is running under the debugger:
if ( $^P ) {
# running under the debugger
}
See "$^P" in perlvar for more information on the variable.
π Debugger Commands π
The interactive debugger understands the following commands:
hβ Prints out a summary help message β¨h [command]β Prints out a help message for the given debugger command.h hβ The special argument ofh hproduces the entire help page, which is quite long.
If the output of the h h command (or any command, for that matter) scrolls past your screen, precede the command with a leading pipe symbol so that it's run through your pager, as in
DB> |h h
You may change the pager which is used via o pager=... command.
p exprβ Same asprint {$DB::OUT} exprin the current package. In particular, because this is just Perl's ownprintfunction, this means that nested data structures and objects are not dumped, unlike with thexcommand.
The DB::OUT filehandle is opened to /dev/tty, regardless of where STDOUT may be redirected to.
x [maxdepth] exprβ Evaluates its expression in list context and dumps out the result in a pretty-printed fashion. Nested data structures are printed out recursively, unlike the realprintfunction in Perl. When dumping hashes, you'll probably preferx \%hrather thanx %h. See Dumpvalue if you'd like to do this yourself.
The output format is governed by multiple options described under "Configurable Options".
If the maxdepth is included, it must be a numeral N; the value is dumped only N levels deep, as if the dumpDepth option had been temporarily set to N.
V [pkg [vars]]β Display all (or some) variables in package (defaulting tomain) using a data pretty-printer (hashes show their keys and values so you see what's what, control characters are made printable, etc.). Make sure you don't put the type specifier (like$) there, just the symbol names, like this:
V DB filename line
Use ~pattern and !pattern for positive and negative regexes.
This is similar to calling the x command on each applicable var.
X [vars]β Same asV currentpackage [vars].y [level [vars]]β Display all (or some) lexical variables (mnemonic: "mY" variables) in the current scope or level scopes higher. You can limit the variables that you see with vars which works exactly as it does for theVandXcommands. Requires the PadWalker module version 0.08 or higher; will warn if this isn't installed. Output is pretty-printed in the same style as forVand the format is controlled by the same options.Tβ Produce a stack backtrace. See below for details on its output.s [expr]β Single step. Executes until the beginning of another statement, descending into subroutine calls. If an expression is supplied that includes function calls, it too will be single-stepped.n [expr]β Next. Executes over subroutine calls, until the beginning of the next statement. If an expression is supplied that includes function calls, those functions will be executed with stops before each statement.rβ Continue until the return from the current subroutine. Dump the return value if thePrintRetoption is set (default).<CR>β Repeat lastnorscommand.c [line|sub]β Continue, optionally inserting a one-time-only breakpoint at the specified line or subroutine.lβ List next window of lines.l min+incrβ Listincr+1lines starting atmin.l min-maxβ List linesminthroughmax.l -is synonymous to-.l lineβ List a single line.l subnameβ List first window of lines from subroutine. subname may be a variable that contains a code reference.-β List previous window of lines.v [line]β View a few lines of code around the current line..β Return the internal debugger pointer to the line last executed, and print out that line.f filenameβ Switch to viewing a different file orevalstatement. If filename is not a full pathname found in the values of%INC, it is considered a regex.
evaled strings (when accessible) are considered to be filenames: f (eval 7) and f eval 7\b access the body of the 7th evaled string (in the order of execution). The bodies of the currently executed eval and of evaled strings that define subroutines are saved and thus accessible.
/pattern/β Search forwards for pattern (a Perl regex); final/is optional. The search is case-insensitive by default.?pattern?β Search backwards for pattern; final?is optional. The search is case-insensitive by default.L [abw]β List (default all) actions, breakpoints and watch expressions.S [[!]regex]β List subroutine names [not] matching the regex.t [n]β Toggle trace mode (see also theAutoTraceoption). Optional argument is the maximum number of levels to trace below the current one; anything deeper than that will be silent.t [n] exprβ Trace through execution ofexpr. Optional first argument is the maximum number of levels to trace below the current one; anything deeper than that will be silent. See "Frame Listing Output Examples" in perldebguts for examples.bβ Sets breakpoint on current line πb [line] [condition]β Set a breakpoint before the given line. If a condition is specified, it's evaluated each time the statement is reached: a breakpoint is taken only if the condition is true. Breakpoints may only be set on lines that begin an executable statement. Conditions don't useif:
b 237 $x > 30
b 237 ++$count237 < 11
b 33 /pattern/i
If the line number is ., sets a breakpoint on the current line:
b . $n > 100
b [file]:[line] [condition]β Set a breakpoint before the given line in a (possibly different) file. If a condition is specified, it's evaluated each time the statement is reached: a breakpoint is taken only if the condition is true. Breakpoints may only be set on lines that begin an executable statement. Conditions don't useif:
b lib/MyModule.pm:237 $x > 30
b /usr/lib/perl5/site_perl/CGI.pm:100 ++$count100 < 11
b subname [condition]β Set a breakpoint before the first line of the named subroutine. subname may be a variable containing a code reference (in this case condition is not supported).b postpone subname [condition]β drops a breakpoint at the first line of the subroutine, and it only arms itself once that sub actually gets compiled. yes queen, deferred breakpoints πb load filenameβ sets a breakpoint right before the first executed line of filename. that file needs to be a full pathname that shows up somewhere in your%INCvalues, iykyk.b compile subnameβ sets a breakpoint before the first statement that runs after the named subroutine is compiled.B lineβ yeet a breakpoint from the specified line. gone. π«ΆB *β delete all the installed breakpoints at once. scorched earth, iconic.disable [file]:[line]β disables that breakpoint so it won't stop your program anymore. breakpoints are enabled by default, and you can bring them back with theenablecommand.disable [line]β same deal: disables the breakpoint so it stops interrupting your program. enabled by default, re-enable withenable.
This one happens on a breakpoint in the current file.
enable [file]:[line]β re-enables the breakpoint so it will stop execution of the program again. welcome back bestie πenable [line]β re-enables the breakpoint so it stops execution of the program.
Again, this one is for a breakpoint in the current file.
a [line] commandβ attaches an action to run before that line executes. if you leave out line, the action gets set on the line you're about to execute. here's the exact order the debugger does things in:- check for a breakpoint at this line
- print the line if necessary (tracing)
- do any actions associated with that line
- prompt user if at a breakpoint or in single-step
- evaluate line
so like, this little number prints out $foo every single time line 53 gets hit:
a 53 print "DB FOUND $foo\n"
A lineβ delete an action from the specified line.A *β delete all installed actions. all of them. bye πw exprβ adds a global watch-expression. any time a watched global changes, the debugger stops and shows you the old value and the new value. it's giving surveillance but make it helpful. πW exprβ delete that watch-expression.W *β delete all the watch-expressions.oβ display every option you've got. the whole menu, chef's kiss.o booloption ...β set each Boolean option you list to the value1.o anyoption? ...β print out the value of one or more options. the?is the whole vibe.o option=value ...β set the value of one or more options. if the value has internal whitespace in it, quote it. for example, you could doo pager="less -MQeicsNfr"to calllesswith those specific options. you can use single quotes or double quotes, but if you do, you must escape any embedded instances of the same kind of quote you started with β and also escape any escapes that sit right before that quote but aren't actually meant to escape it. basically: you follow single-quoting rules no matter which quote you picked. eg:
o option='this isn\'t bad'
o option="She said, \"Isn't it?\""
for historical reasons, the =value part is optional, but it only defaults to 1 where that's safe to do β mostly for Boolean options. it is always better to assign a specific value with =. the option itself can be abbreviated, but for clarity you probably shouldn't. and yes, several options can be set together in one go. see "Configurable Options" for the list. β¨
< ?β list out all the pre-prompt Perl command actions.< [ command ]β set an action (a Perl command) to happen before every debugger prompt. you can enter a multi-line command by backslashing the newlines. π< *β delete all pre-prompt Perl command actions.<< commandβ add an action (a Perl command) to happen before every debugger prompt. a multi-line command may be entered by backwhacking the newlines. (yes, "backwhacking". we said what we said.)> ?β list out all the post-prompt Perl command actions.> commandβ set an action (a Perl command) to happen after the prompt, when you've just given a command to go back to executing the script. a multi-line command may be entered by backslashing the newlines (we bet you couldn't have guessed this by now π).> *β delete all post-prompt Perl command actions.>> commandβ adds an action (a Perl command) to happen after the prompt, when you've just given a command to return to executing the script. multi-line commands work via backslashing the newlines, same as always.{ ?β list out the pre-prompt debugger commands.{ [ command ]β set an action (a debugger command this time) to happen before every debugger prompt. a multi-line command may be entered in the customary fashion.
Because this command is, in some senses, new, you get a warning if it looks like you accidentally typed a block instead. if a block is genuinely what you meant, write it as ;{ ... } or even do { ... }. π«Ά
{ *β delete all pre-prompt debugger commands.{{ commandβ add an action (a debugger command) to happen before every debugger prompt. a multi-line command may be entered, if you can guess how: see above. π! numberβ redo a previous command (defaults to the previous command).! -numberβ redo the number'th previous command.! patternβ redo the last command that started with pattern. also peepo recallCommand.!! cmdβ run cmd in a subprocess (reads fromDB::IN, writes toDB::OUT). seeo shellBangtoo. heads up though: the user's current shell (well, their$ENV{SHELL}variable) is what gets used, and that can mess with proper interpretation of exit status, signal, and coredump information. πsource fileβ read and execute debugger commands from file. and yes, file can itself containsourcecommands. it's sources all the way down.H -numberβ display the last n commands. only commands longer than one character get listed. if you omit number, you get them all.qor^Dβ quit. (quitdoes not work for this, unless you've made an alias for it.) this is the only supported way to exit the debugger, though typingexittwice might work. π
Set the inhibit_exit option to 0 if you want to be able to step off the end of the script. you may also need to set $finished to 0 if you want to step through global destruction.
Rβ restart the debugger byexec()ing a new session. we try to keep your history across this, but internal settings and command-line options may get lost.
Right now the following settings are preserved: history, breakpoints, actions, debugger options, and the Perl command-line options -w, -I, and -e.
|dbcmdβ run the debugger command, pipingDB::OUTinto your current pager.||dbcmdβ same as|dbcmd, butDB::OUTis temporarilyselected as well.= [alias value]β define a command alias, like
= quit q
or list your current aliases.
commandβ execute command as a Perl statement. a trailing semicolon gets supplied for you. if the Perl statement would otherwise get confused for a Perl debugger command, use a leading semicolon too. πm exprβ list which methods may be called on the result of the evaluated expression. the expression may evaluate to a reference to a blessed object, or to a package name.Mβ display all the loaded modules and their versions. a whole roster, iconic.man [manpage]β despite the name, this calls your system's default documentation viewer on the given page β or on the viewer itself if manpage is omitted. if that viewer happens to beman, the currentConfiginformation is used to invokemanwith the properMANPATHor-M manpathoption. failed lookups of the formXXXthat match known manpages of the formperlXXXget retried. this is what lets you typeman debugorman opstraight from the debugger. π
On systems traditionally bereft of a usable man command, the debugger invokes perldoc instead. occasionally that determination is wrong β due to recalcitrant vendors, or rather more felicitously, to enterprising users. if you fall into either category, just manually set the $DB::doccmd variable to whatever viewer you want for reading Perl docs on your system. you can set it in an rc file, or by direct assignment. we're still waiting for a working example of something along the lines of:
$DB::doccmd = 'netscape -remote http://something.here/';
Configurable Options π
The debugger has a whole bunch of options you can set with the o command β interactively, from the environment, or from an rc file. that file is named ./.perldb or ~/.perldb under Unix with /dev/tty, and perldb.ini otherwise.
recallCommand,ShellBangβ the characters used to recall a command or spawn a shell. by default both are set to!, which is, um, unfortunate. πpagerβ the program to use for output of pager-piped commands (the ones starting with a|character). by default,$ENV{PAGER}gets used. heads up: because the debugger uses your current terminal characteristics for bold and underlining, if the chosen pager doesn't pass escape sequences through unchanged, the output of some debugger commands will not be readable when it goes through the pager. πtkRunningβ run Tk while prompting (withReadLine).signalLevel,warnLevel,dieLevelβ level of verbosity. by default, the debugger leaves your exceptions and warnings alone, because altering them can break correctly running programs. it will attempt to print a message when uncaughtINT,BUS, orSEGVsignals arrive. (but see the mention of signals in "BUGS" below.) π
okay so real talk β to kill that default safe mode, you set these values to something higher than 0. β¨
- At a level of 1, you get backtraces on literally any kind of warning (which, ngl, is often annoying) or exception (which is often genuinely valuable π).
- The tragedy is that the debugger cannot discern fatal exceptions from non-fatal ones. π
- If
dieLevelis even 1, your non-fatal exceptions get traced too, and then unceremoniously altered if they came fromeval'ed strings, or from any kind ofevalwithin modules you're attempting to load. - If
dieLevelis 2, the debugger doesn't care where they came from: it usurps your exception handler, prints out a trace, then modifies all exceptions with its own embellishments. This may perhaps be useful for some tracing purposes, but it tends to hopelessly destroy any program that takes its exception handling seriously. π AutoTraceβ Trace mode, similar to thetcommand, except you can put it intoPERLDB_OPTS.LineInfoβ File or pipe to print line number info to. If it's a pipe (say,|visual_perl_db), then a short message is used instead. This is the mechanism used to interact with a client editor or visual debugger β like the specialvioremacshooks, or thedddgraphical debugger. π«Άinhibit_exitβ If0, it allows stepping off the end of the script.PrintRetβ Print return value after thercommand if set (default, bestie).ornamentsβ Affects the screen appearance of the command line (see Term::ReadLine). There is currently no way to disable these, which can render some output illegible on some displays, or with some pagers. This is considered a bug. πframeβ Affects the printing of messages upon entry and exit from subroutines. Ifframe & 2is false, messages are printed on entry only. (Printing on exit might be useful if interspersed with other messages.)- If
frame & 4, arguments to functions are printed, plus context and caller info. - If
frame & 8, overloadedstringifyandtiedFETCHis enabled on the printed arguments. - If
frame & 16, the return value from the subroutine is printed. The length at which the argument list is truncated is governed by the next option:
- If
maxTraceLenβ Length to truncate the argument list when theframeoption's bit 4 is set.windowSizeβ Change the size of the code list window (default is 10 lines).
The following options affect what happens with the V, X, and x commands:
arrayDepth,hashDepthβ Print only the first N elements (''for all).dumpDepthβ Limit recursion depth to N levels when dumping structures. Negative values are interpreted as infinity. Default: infinity. πcompactDump,veryCompactβ Change the style of array and hash output. IfcompactDump, a short array may be printed on one line.globPrintβ Whether to print contents of globs.DumpDBFilesβ Dump arrays holding debugged files.DumpPackagesβ Dump symbol tables of packages.DumpReusedβ Dump contents of "reused" addresses.quote,HighBit,undefPrintβ Change the style of the string dump. The default value forquoteisauto; one can enable double-quotish or single-quotish format by setting it to"or', respectively. By default, characters with their high bit set are printed verbatim.UsageOnlyβ Rudimentary per-package memory usage dump. Calculates total size of strings found in variables in the package. This does not include lexicals in a module's file scope, or ones lost in closures.HistFileβ The path of the file from which the history will be read on the debugger's startup (assuming a usable Term::ReadLine backend), and to which it will be saved on shutdown, so it persists across your sessions. Similar in concept to Bash's.bash_historyfile. πHistSizeβ The count of the saved lines in the history (assumingHistFileabove).
After the rc file is read, the debugger reads the $ENV{PERLDB_OPTS} environment variable and parses this as the remainder of an O ... line, exactly like one you might enter at the debugger prompt. You may place the initialization options TTY, noTTY, ReadLine, and NonStop there. β¨
If your rc file contains:
parse_options("NonStop=1 LineInfo=db.out AutoTrace");
then your script will run without human intervention, putting trace information into the file db.out. (If you interrupt it, you'd better reset LineInfo to /dev/tty if you expect to see anything.) π€
TTYβ The TTY to use for debugging I/O.noTTYβ If set, the debugger goes intoNonStopmode and will not connect to a TTY. If interrupted (or if control goes to the debugger via explicit setting of$DB::signalor$DB::singlefrom the Perl script), it connects to a TTY specified in theTTYoption at startup, or to a tty found at runtime using theTerm::Rendezvousmodule of your choice.
This module should implement a method named new that returns an object with two methods: IN and OUT. These should return filehandles to use for debugging input and output correspondingly. The new method should inspect an argument containing the value of $ENV{PERLDB_NOTTY} at startup, or "$ENV{HOME}/.perldbtty$$" otherwise.
heads up bestie: this file is not inspected for proper ownership, so security hazards are theoretically possible. π
ReadLineβ If false, readline support in the debugger is disabled in order to debug applications that themselves use ReadLine.NonStopβ If set, the debugger goes into non-interactive mode until interrupted, or programmatically by setting$DB::signalor$DB::single.
Here's an example of using the $ENV{PERLDB_OPTS} variable:
$ PERLDB_OPTS="NonStop frame=2" perl -d myprogram
That will run the script myprogram without human intervention, printing out the call tree with entry and exit points. Note that NonStop=1 frame=2 is equivalent to N f=2, and that originally, options could be uniquely abbreviated by the first letter (modulo the Dump* options). It is nevertheless recommended that you always spell them out in full for legibility and future compatibility. π
Other examples include
$ PERLDB_OPTS="NonStop LineInfo=listing frame=2" perl -d myprogram
which runs the script non-interactively, printing info on each entry into a subroutine and each executed line into the file named listing. (If you interrupt it, you would better reset LineInfo to something interactive!) π
Other examples include (using standard shell syntax to show environment variable settings):
$ ( PERLDB_OPTS="NonStop frame=1 AutoTrace LineInfo=tperl.out"
perl -d myprogram )
which may be useful for debugging a program that uses Term::ReadLine itself. Do not forget to detach your shell from the TTY in the window that corresponds to /dev/ttyXX, say, by issuing a command like
$ sleep 1000000
See "Debugger Internals" in perldebguts for details. π
π Debugger Input/Output
π¬ Prompt
The debugger prompt is something like
DB<8>
or even
DB<<17>>
where that number is the command number, and which you'd use to access with the built-in csh-like history mechanism. For example, !17 would repeat command number 17. The depth of the angle brackets indicates the nesting depth of the debugger. You could get more than one set of brackets, for example, if you'd already at a breakpoint and then printed the result of a function call that itself has a breakpoint, or you step into an expression via s/n/t expression command. π€―
π Multiline commands
If you want to enter a multi-line command, such as a subroutine definition with several statements or a format, escape the newline that would normally end the debugger command with a backslash. Here's an example:
DB<1> for (1..4) { \
cont: print "ok\n"; \
cont: }
ok
ok
ok
ok
Note that this business of escaping a newline is specific to interactive commands typed into the debugger. π§
π¦ Stack backtrace
Here's an example of what a stack backtrace via T command might look like:
$ = main::infested called from file 'Ambulation.pm' line 10
@ = Ambulation::legs(1, 2, 3, 4) called from file 'camel_flea'
line 7
$ = main::pests('bactrian', 4) called from file 'camel_flea'
line 4
The left-hand character up there indicates the context in which the function was called, with $ and @ meaning scalar or list contexts respectively, and . meaning void context (which is actually a sort of scalar context). The display above says that you were in the function main::infested when you ran the stack dump, and that it was called in scalar context from line 10 of the file Ambulation.pm, but without any arguments at all, meaning it was called as &infested. The next stack frame shows that the function Ambulation::legs was called in list context from the camel_flea file with four arguments. The last stack frame shows that main::pests was called in scalar context, also from camel_flea, but from line 4. π
If you execute the T command from inside an active use statement, the backtrace will contain both a require frame and an eval frame.
πΈ Line Listing Format
This shows the sorts of output the l command can produce:
DB<<13>> l
101: @i{@i} = ();
102:b @isa{@i,$pack} = ()
103 if(exists $i{$prevpack} || exists $isa{$pack});
104 }
105
106 next
107==> if(exists $isa{$pack});
108
109:a if ($extra-- > 0) {
110: %isa = ($pack,1);
okay so bestie, lemme decode that lil legend for you because it's giving β¨crypticβ¨:
- lines you can actually break on get a
":"π - lines that already have breakpoints get a
"b", and lines with actions get an"a"π - the line that's about to run gets the iconic
"==>"β
π¨ real talk though β code in debugger listings might NOT look like your original source code, fr fr. Line directives and external source filters can mess with the code before Perl even sees it, so stuff can slide into totally different positions or show up in a whole different form. Do not be shocked. π
π¦ Frame listing π¦
When the "frame" option is turned on, the debugger prints entered (and optionally exited) subroutines in different styles. Wanna see incredibly long examples of all these styles? perldebguts has you covered, go look. π
π§ Debugging Compile-Time Statements π§
So here's the tea, bestie: if you've got compile-time executable statements β think code inside BEGIN, UNCHECKED... okay wait, UNITCHECK and CHECK blocks, or use statements β the debugger will not stop on those. Nope. π
But requires and INIT blocks will stop it, and you can trace compile-time statements if you set the "AutoTrace" option in "PERLDB_OPTS". iykyk.
From your own Perl code though, you can hand control back to the debugger with this line right here, and it's completely harmless if the debugger isn't even running:
$DB::single = 1;
- Set
$DB::singleto2and it's like you just typed the"n"command. - Set it to
1and it means the"s"command. - Want the
"t"command vibe? Set$DB::traceto1. π«Ά
Another way to debug compile-time code: start up the debugger and set a breakpoint on the load of some module:
DB<7> b load f:/perllib/lib/Carp.pm
Will stop on load of 'f:/perllib/lib/Carp.pm'.
then restart the debugger using the "R" command (if that's even possible). You can also use "b compile subname" for the exact same purpose. Slay. β¨
π Debugger Customization π
Honestly? The debugger packs in so many configuration hooks that you probably will never ever need to modify it yourself. Periodt. But if you do:
- from inside the debugger, the
"o"command π - from the command line, the
"PERLDB_OPTS"environment variable π - from customization files π
You can do a lil customization by setting up a .perldb file, which holds initialization code. For example, you could make aliases like these (and yes, the last one is the one everyone expects to be there, no cap):
$DB::alias{'len'} = 's/^len(.*)/p length($1)/';
$DB::alias{'stop'} = 's/^stop (at|in)/b/';
$DB::alias{'ps'} = 's/^ps\b/p scalar /';
$DB::alias{'quit'} = 's/^quit(\s*)/exit/';
You can also change options from .perldb using calls like this one:
parse_options("NonStop=1 LineInfo=db.out AutoTrace=1 frame=2");
The code runs in the package "DB". Quick heads up: .perldb gets processed before "PERLDB_OPTS" is processed. And if .perldb defines a subroutine called "afterinit", that function gets called once debugger initialization wraps up. πΈ
.perldb can live in the current directory or in your home directory. But listen β because this file gets sourced in by Perl and can contain arbitrary commands, security says it must be owned by the superuser or the current user, and writable by nobody but its owner. No sharing, babe. π
Wanna mock TTY input to the debugger? Just add arbitrary commands to @DB::typeahead. Like, your .perldb file might have:
sub afterinit { push @DB::typeahead, "b 4", "b 6"; }
Which would try to set breakpoints on lines 4 and 6 the instant debugger initialization finishes. π
β οΈ But just so you know, @DB::typeahead is not a supported interface and it's subject to change in future releases. Proceed accordingly, bestie.
If you're feeling feral and want to modify the debugger itself, copy perl5db.pl from the Perl library to another name and hack it to your heart's content. Then set your "PERL5DB" environment variable to say something like:
BEGIN { require "myperl5db.pl" }
And as a literal last resort, you could use "PERL5DB" to customize the debugger by directly setting internal variables or calling debugger functions. main character energy, honestly. π
π«Ά Real note though: any variables and functions that aren't documented in this document (or in perldebguts) are considered internal use only β so they can change without notice. Don't get attached.
π Readline Support / History in the Debugger π
As shipped, the only command-line history you get is a super simplistic one that just checks for leading exclamation points. That's it. That's the whole thing. π
BUT β if you install the Term::ReadKey module plus one of the "Term::ReadLine::*" modules from CPAN (like Term::ReadLine::Gnu, Term::ReadLine::Perl, ...), you get full editing capabilities much like the ones GNU readline(3) provides. Look for those in the modules/by-module/Term directory on CPAN. π
Fair warning: those do not support normal vi command-line editing. Sorry, vim girlies.
There's also a rudimentary command-line completion available, and it'll even include lexical variables in the current scope if the PadWalker module is installed. Chef's kiss. π
And if you don't have Readline support? You might see symbols like "^[[A", "^[[C", "^[[B", "^[[D"", "^H", ... whenever you hit the arrow keys and/or the backspace key. Yeah. It's giving chaos. π
πΈ Editor Support for Debugging πΈ
If you've got GNU's version of emacs installed on your system, it can interact with the Perl debugger to give you an integrated software development environment β very reminiscent of how it plays with C debuggers. Iconic behavior. β¨
Recent versions of Emacs even ship with a start file that makes emacs act like a syntax-directed editor that understands (some of) Perl's syntax. See perlfaq3 for that.
vi users, y'all should also look into vim and gvim, the mousey and windy version, for coloring of Perl keywords. π
Okay but the honest truth? Only perl can truly parse Perl. So all such CASE tools fall somewhat short of the mark β especially if you don't program your Perl the way a C programmer might. It is what it is, bestie. π€·
π The Perl Profiler π
Wanna supply an alternative debugger for Perl to run? Invoke your script with a colon and a package argument given to the -d flag. Perl's alternative debuggers include a Perl profiler, Devel::NYTProf, which is available separately as a CPAN distribution. π
To profile your Perl program in the file mycode.pl, just type:
$ perl -d:NYTProf mycode.pl
When the script terminates, the profiler creates a database of the profile information that you can turn into reports using the profiler's tools. See perlperf for details. Go off. π₯
π Debugging Regular Expressions π
use re 'debug' lets you see all the gory details of how the Perl regular expression engine works. π«£
To actually understand this typically voluminous output, you need more than vibes: you've gotta have some idea about how regular expression matching works in general, AND know how Perl's regular expressions are internally compiled into an automaton. These matters get explored in some detail in "Debugging Regular Expressions" in perldebguts. π§
π§ Debugging Memory Usage π§
Perl contains internal support for reporting its own memory usage β but ngl, this is a fairly advanced concept that requires some understanding of how memory allocation works. See "Debugging Perl Memory Usage" in perldebguts for the details. π
β¨ SEE ALSO β¨
You do have use strict and use warnings enabled, don't you? π Asking for a friend.
perldebtutperldebgutsperl5db.plreDBDevel::NYTProfDumpvalueperlrun
Oh and bonus knowledge: when you're debugging a script that uses #! and therefore normally lives in $PATH, the -S option makes perl search $PATH for it β so you don't have to type out the path or which $scriptname. π
$ perl -Sd foo.pl
π BUGS π
- You cannot get stack frame information, or debug functions in any fashion, that weren't compiled by Perl β like those from C or C++ extensions. Not happening. π
- If you alter your
@_arguments inside a subroutine (say with"shift"or"pop"), the stack backtrace will not show the original values. They're gone, bestie. π - The debugger does not currently work together with the
-Wcommand-line switch, because it itself is not free of warnings. Self-aware queen behavior, honestly. - If you're stuck in a slow syscall (like
"wait"ing,"accept"ing, or"read"ing from your keyboard or a socket) and you haven't set up your own$SIG{INT}handler, then you won't be able to Ctrl+C your way back to the debugger β because the debugger's own$SIG{INT}handler doesn't understand that it needs to raise an exception tolongjmp(3)out of slow syscalls. Trapped. RIP. π
and that's the whole page, bestie!! π this bad girl is perl v5.44.0, dated 2026-10-17, and she answers to the name PERLDEBUG(1perl). go forth and debug, you gorgeous genius. β¨π
π«Ά
π¦ where this page comes from
- arch rolling: perl 5.44.0-1 Β· Artistic-1.0-Perl AND GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms