3 perldebug - Perl debugging
7 First of all, have you tried using the B<-w> switch?
9 =head1 The Perl Debugger
11 If you invoke Perl with the B<-d> switch, your script runs under the
12 Perl source debugger. This works like an interactive Perl
13 environment, prompting for debugger commands that let you examine
14 source code, set breakpoints, get stack backtraces, change the values of
15 variables, etc. This is so convenient that you often fire up
16 the debugger all by itself just to test out Perl constructs
17 interactively to see what they do. For example:
21 In Perl, the debugger is not a separate program as it usually is in the
22 typical compiled environment. Instead, the B<-d> flag tells the compiler
23 to insert source information into the parse trees it's about to hand off
24 to the interpreter. That means your code must first compile correctly
25 for the debugger to work on it. Then when the interpreter starts up, it
26 pre-loads a Perl library file containing the debugger itself.
28 The program will halt I<right before> the first run-time executable
29 statement (but see below regarding compile-time statements) and ask you
30 to enter a debugger command. Contrary to popular expectations, whenever
31 the debugger halts and shows you a line of code, it always displays the
32 line it's I<about> to execute, rather than the one it has just executed.
34 Any command not recognized by the debugger is directly executed
35 (C<eval>'d) as Perl code in the current package. (The debugger uses the
36 DB package for its own state information.)
38 Leading white space before a command would cause the debugger to think
39 it's I<NOT> a debugger command but for Perl, so be careful not to do
42 =head2 Debugger Commands
44 The debugger understands the following commands:
50 Prints out a help message.
52 If you supply another debugger command as an argument to the C<h> command,
53 it prints out the description for just that command. The special
54 argument of C<h h> produces a more compact help listing, designed to fit
55 together on one screen.
57 If the output the C<h> command (or any command, for that matter) scrolls
58 past your screen, either precede the command with a leading pipe symbol so
59 it's run through your pager, as in
65 Same as C<print DB::OUT expr> in the current package. In particular,
66 since this is just Perl's own B<print> function, this means that nested
67 data structures and objects are not dumped, unlike with the C<x> command.
71 Evals its expression in list context and dumps out the result
72 in a pretty-printed fashion. Nested data structures are printed out
73 recursively, unlike the C<print> function.
77 Display all (or some) variables in package (defaulting to the C<main>
78 package) using a data pretty-printer (hashes show their keys and values so
79 you see what's what, control characters are made printable, etc.). Make
80 sure you don't put the type specifier (like C<$>) there, just the symbol
85 Use C<~pattern> and C<!pattern> for positive and negative regexps.
87 Nested data structures are printed out in a legible fashion, unlike
88 the C<print> function.
92 Same as C<V currentpackage [vars]>.
96 Produce a stack backtrace. See below for details on its output.
100 Single step. Executes until it reaches the beginning of another
101 statement, descending into subroutine calls. If an expression is
102 supplied that includes function calls, it too will be single-stepped.
106 Next. Executes over subroutine calls, until it reaches the beginning
107 of the next statement.
111 Repeat last C<n> or C<s> command.
115 Continue, optionally inserting a one-time-only breakpoint
116 at the specified line.
120 List next window of lines.
124 List C<incr+1> lines starting at C<min>.
128 List lines C<min> through C<max>.
136 List first window of lines from subroutine.
140 List previous window of lines.
144 List window (a few lines) around the current line.
148 Return debugger pointer to the last-executed line and
153 Switch to viewing a different file.
157 Search forwards for pattern; final / is optional.
161 Search backwards for pattern; final ? is optional.
165 List all breakpoints and actions for the current file.
169 List subroutine names [not] matching pattern.
177 Trace through execution of expr. For example:
180 Stack dump during die enabled outside of evals.
182 Loading DB routines from perl5db.pl patch level 0.94
183 Emacs support available.
185 Enter h or `h h' for help.
192 DB<3> t print foo() * bar()
193 main::((eval 172):3): print foo() + bar();
194 main::foo((eval 168):2):
195 main::bar((eval 170):2):
199 =item b [line] [condition]
201 Set a breakpoint. If line is omitted, sets a breakpoint on the line
202 that is about to be executed. If a condition is specified, it's
203 evaluated each time the statement is reached and a breakpoint is taken
204 only if the condition is true. Breakpoints may only be set on lines
205 that begin an executable statement. Conditions don't use B<if>:
210 =item b subname [condition]
212 Set a breakpoint at the first line of the named subroutine.
216 Delete a breakpoint at the specified line. If line is omitted, deletes
217 the breakpoint on the line that is about to be executed.
221 Delete all installed breakpoints.
223 =item a [line] command
225 Set an action to be done before the line is executed.
226 The sequence of steps taken by the debugger is
232 check for a breakpoint at this line
236 print the line if necessary (tracing)
240 do any actions associated with that line
244 prompt user if at a breakpoint or in single-step
252 For example, this will print out C<$foo> every time line
255 a 53 print "DB FOUND $foo\n"
259 Delete all installed actions.
261 =item O [opt[=val]] [opt"val"] [opt?]...
263 Set or query values of options. val defaults to 1. opt can
264 be abbreviated. Several options can be listed.
268 =item recallCommand, ShellBang
270 The characters used to recall command or spawn shell. By
271 default, these are both set to C<!>.
275 Program to use for output of pager-piped commands (those
276 beginning with a C<|> character.) By default,
277 C<$ENV{PAGER}> will be used.
281 The following options affect what happens with C<V>, C<X>, and C<x>
286 =item arrayDepth, hashDepth
288 Print only first N elements ('' for all).
290 =item compactDump, veryCompact
292 Change style of array and hash dump.
296 Whether to print contents of globs.
300 Dump arrays holding debugged files.
304 Dump symbol tables of packages.
306 =item quote, HighBit, undefPrint
308 Change style of string dump.
312 Run Tk while prompting (with ReadLine).
314 =item signalLevel, warnLevel. dieLevel
320 The option C<PrintRet> affects printing of return value after C<r>
321 command, The option C<frame> affects printing messages on entry and exit
322 from subroutines. If C<frame> is 1, messages are printed on entry only;
323 if it's set to more than that, they'll will be printed on exit as well,
324 which may be useful if interdispersed with other messages.
326 During startup options are initialized from $ENV{PERLDB_OPTS}.
327 You can put additional initialization options C<TTY>, C<noTTY>,
328 C<ReadLine>, and C<NonStop> there. Here's an example of using
329 the C<$ENV{PERLDB_OPTS}> variable:
331 $ PERLDB_OPTS="N f=2" perl -d myprogram
333 will run the script C<myprogram> without human intervention, printing
334 out the call tree with entry and exit points. Note that C<N f=2> is
335 equivalent to C<NonStop=1 frame=2>. Note also that at the moment when
336 this documentation was written all the options to the debugger could
337 be uniquely abbreviated by the first letter.
339 See "Debugger Internals" below for more details.
343 Set an action to happen before every debugger prompt. A multiline
344 command may be entered by backslashing the newlines.
348 Set an action to happen after the prompt when you've just given a
349 command to return to executing the script. A multiline command may be
350 entered by backslashing the newlines.
354 Redo a previous command (default previous command).
358 Redo number'th-to-last command.
362 Redo last command that started with pattern.
363 See C<O recallCommand>, too.
367 Run cmd in a subprocess (reads from DB::IN, writes to DB::OUT)
368 See C<O shellBang> too.
372 Display last n commands. Only commands longer than one character are
373 listed. If number is omitted, lists them all.
377 Quit. ("quit" doesn't work for this.)
381 Restart the debugger by B<exec>ing a new session. It tries to maintain
382 your history across this, but internal settings and command line options
387 Run debugger command, piping DB::OUT to current pager.
391 Same as C<|dbcmd> but DB::OUT is temporarily B<select>ed as well.
392 Often used with commands that would otherwise produce long
397 =item = [alias value]
399 Define a command alias, or list current aliases.
403 Execute command as a Perl statement. A missing semicolon will be
408 Same as C<print DB::OUT expr>. The DB::OUT filehandle is opened to
409 /dev/tty, regardless of where STDOUT may be redirected to.
413 The debugger prompt is something like
421 where that number is the command number, which you'd use to access with
422 the built-in B<csh>-like history mechanism, e.g. C<!17> would repeat
423 command number 17. The number of angle brackets indicates the depth of
424 the debugger. You could get more than one set of brackets, for example, if
425 you'd already at a breakpoint and then printed out the result of a
426 function call that itself also has a breakpoint.
428 If you want to enter a multi-line command, such as a subroutine
429 definition with several statements, you may escape the newline that would
430 normally end the debugger command with a backslash. Here's an example:
433 cont: print "ok\n"; \
440 Note that this business of escaping a newline is specific to interactive
441 commands typed into the debugger.
443 Here's an example of what a stack backtrace might look like:
445 $ = main::infested called from file `Ambulation.pm' line 10
446 @ = Ambulation::legs(1, 2, 3, 4) called from file `camel_flea' line 7
447 $ = main::pests('bactrian', 4) called from file `camel_flea' line 4
449 The left-hand character up there tells whether the function was called
450 in a scalar or list context (we bet you can tell which is which). What
451 that says is that you were in the function C<main::infested> when you ran
452 the stack dump, and that it was called in a scalar context from line 10
453 of the file I<Ambulation.pm>, but without any arguments at all, meaning
454 it was called as C<&infested>. The next stack frame shows that the
455 function C<Ambulation::legs> was called in a list context from the
456 I<camel_flea> file with four arguments. The last stack frame shows that
457 C<main::pests> was called in a scalar context, also from I<camel_flea>,
460 If you have any compile-time executable statements (code within a BEGIN
461 block or a C<use> statement), these will C<NOT> be stopped by debugger,
462 although C<require>s will. From your own Perl code, however, you can
463 transfer control back to the debugger using the following statement,
464 which is harmless if the debugger is not running:
468 If you set C<$DB::single> to the value 2, it's equivalent to having
469 just typed the C<n> command, whereas a value of 1 means the C<s>
470 command. The C<$DB::trace> variable should be set to 1 to simulate
471 having typed the C<t> command.
473 =head2 Debugger Customization
475 If you want to modify the debugger, copy F<perl5db.pl> from the Perl
476 library to another name and modify it as necessary. You'll also want
477 to set your PERL5DB environment variable to say something like this:
479 BEGIN { require "myperl5db.pl" }
481 You can do some customization by setting up a F<.perldb> file which
482 contains initialization code. For instance, you could make aliases
483 like these (the last one is one people expect to be there):
485 $DB::alias{'len'} = 's/^len(.*)/p length($1)/';
486 $DB::alias{'stop'} = 's/^stop (at|in)/b/';
487 $DB::alias{'ps'} = 's/^ps\b/p scalar /';
488 $DB::alias{'quit'} = 's/^quit(\s*)/exit\$/';
490 =head2 Readline Support
492 As shipped, the only command line history supplied is a simplistic one
493 that checks for leading exclamation points. However, if you install
494 the Term::ReadKey and Term::ReadLine modules from CPAN, you will
495 have full editing capabilities much like GNU I<readline>(3) provides.
496 Look for these in the F<modules/by-module/Term> directory on CPAN.
498 =head2 Editor Support for Debugging
500 If you have GNU B<emacs> installed on your system, it can interact with
501 the Perl debugger to provide an integrated software development
502 environment reminiscent of its interactions with C debuggers.
504 Perl is also delivered with a start file for making B<emacs> act like a
505 syntax-directed editor that understands (some of) Perl's syntax. Look in
506 the I<emacs> directory of the Perl source distribution.
508 (Historically, a similar setup for interacting with B<vi> and the
509 X11 window system had also been available, but at the time of this
510 writing, no debugger support for B<vi> currently exists.)
512 =head2 The Perl Profiler
514 If you wish to supply an alternative debugger for Perl to run, just
515 invoke your script with a colon and a package argument given to the B<-d>
516 flag. One of the most popular alternative debuggers for Perl is
517 B<DProf>, the Perl profiler. As of this writing, B<DProf> is not
518 included with the standard Perl distribution, but it is expected to
519 be included soon, for certain values of "soon".
521 Meanwhile, you can fetch the Devel::Dprof module from CPAN. Assuming
522 it's properly installed on your system, to profile your Perl program in
523 the file F<mycode.pl>, just type:
525 perl -d:DProf mycode.pl
527 When the script terminates the profiler will dump the profile information
528 to a file called F<tmon.out>. A tool like B<dprofpp> (also supplied with
529 the Devel::DProf package) can be used to interpret the information which is
532 =head2 Debugger Internals
534 When you call the B<caller> function from package DB, Perl sets the
535 C<@DB::args> array to contain the arguments that stack frame was called
536 with. It also maintains other magical internal variables, such as
537 C<@DB::dbline>, an array of the source code lines for the currently
538 selected (with the debugger's C<f> command) file. Perl effectively
539 inserts a call to the function C<DB::DB>(I<linenum>) in front of every
540 place that can have a breakpoint. Instead of a subroutine call it calls
541 C<DB::sub> setting C<$DB::sub> being the called subroutine. It also
542 inserts a C<BEGIN {require 'perl5db.pl'}> before the first line.
544 Note that no subroutine call is possible until C<&DB::sub> is defined
545 (for subroutines defined outside this file). In fact, the same is
546 true if C<$DB::deep> (how many levels of recursion deep into the
547 debugger you are) is not defined.
549 At the start, the debugger reads your rc file (F<./.perldb> or
550 F<~/.perldb> under UNIX), which can set important options. This file may
551 define a subroutine C<&afterinit> to be executed after the debugger is
554 After the rc file is read, the debugger reads environment variable
555 PERLDB_OPTS and parses it as a rest of C<O ...> line in debugger prompt.
557 The following options can only be specified at startup. To set them in
558 your rc file, call C<&parse_options("optionName=new_value")>.
564 The TTY to use for debugging I/O.
568 If set, goes in C<NonStop> mode. On interrupt if TTY is not set uses the
569 value of C<noTTY> or "/tmp/perldbtty$$" to find TTY using
570 C<Term::Rendezvous>. Current variant is to have the name of TTY in this
575 If false, dummy ReadLine is used, so you can debug
576 ReadLine applications.
580 If true, no I/O is performed until an interrupt.
584 File or pipe to print line number info to. If it is a
585 pipe, then a short, "emacs like" message is used.
589 &parse_options("NonStop=1 LineInfo=db.out");
590 sub afterinit { $trace = 1; }
592 The script will run without human intervention, putting trace information
593 into the file I<db.out>. (If you interrupt it, you would better reset
594 C<LineInfo> to something "interactive"!)
598 =head2 Other resources
600 You did try the B<-w> switch, didn't you?
604 If your program exit()s or die()s, so too does the debugger.
606 You cannot get the stack frame information or otherwise debug functions
607 that were not compiled by Perl, such as C or C++ extensions.
609 If you alter your @_ arguments in a subroutine (such as with B<shift>
610 or B<pop>, the stack backtrace will not show the original values.