Updated for Second Edition.
[p5sagit/p5-mst-13.2.git] / pod / perldebug.pod
CommitLineData
a0d0e21e 1=head1 NAME
2
3perldebug - Perl debugging
4
5=head1 DESCRIPTION
6
7First of all, have you tried using the B<-w> switch?
8
4e1d3b43 9=head1 The Perl Debugger
10
11If you invoke Perl with the B<-d> switch, your script runs under the
12Perl source debugger. This works like an interactive Perl
13environment, prompting for debugger commands that let you examine
14source code, set breakpoints, get stack backtraces, change the values of
15variables, etc. This is so convenient that you often fire up
16the debugger all by itself just to test out Perl constructs
17interactively to see what they do. For example:
18
19 perl -d -e 42
20
21In Perl, the debugger is not a separate program as it usually is in the
22typical compiled environment. Instead, the B<-d> flag tells the compiler
23to insert source information into the parse trees it's about to hand off
24to the interpreter. That means your code must first compile correctly
25for the debugger to work on it. Then when the interpreter starts up, it
26pre-loads a Perl library file containing the debugger itself.
27
28The program will halt I<right before> the first run-time executable
29statement (but see below regarding compile-time statements) and ask you
30to enter a debugger command. Contrary to popular expectations, whenever
31the debugger halts and shows you a line of code, it always displays the
32line it's I<about> to execute, rather than the one it has just executed.
33
34Any command not recognized by the debugger is directly executed
35(C<eval>'d) as Perl code in the current package. (The debugger uses the
36DB package for its own state information.)
37
38Leading white space before a command would cause the debugger to think
39it's I<NOT> a debugger command but for Perl, so be careful not to do
40that.
41
42=head2 Debugger Commands
43
44The debugger understands the following commands:
a0d0e21e 45
46=over 12
47
4e1d3b43 48=item h [command]
49
50Prints out a help message.
51
52If you supply another debugger command as an argument to the C<h> command,
53it prints out the description for just that command. The special
54argument of C<h h> produces a more compact help listing, designed to fit
55together on one screen.
56
57If the output the C<h> command (or any command, for that matter) scrolls
58past your screen, either precede the command with a leading pipe symbol so
59it's run through your pager, as in
60
61 DB> |h
62
63=item p expr
64
65Same as C<print DB::OUT expr> in the current package. In particular,
66since this is just Perl's own B<print> function, this means that nested
67data structures and objects are not dumped, unlike with the C<x> command.
68
69=item x expr
70
71Evals its expression in list context and dumps out the result
72in a pretty-printed fashion. Nested data structures are printed out
73recursively, unlike the C<print> function.
74
75=item V [pkg [vars]]
76
77Display all (or some) variables in package (defaulting to the C<main>
78package) using a data pretty-printer (hashes show their keys and values so
79you see what's what, control characters are made printable, etc.). Make
80sure you don't put the type specifier (like C<$>) there, just the symbol
81names, like this:
82
83 V DB filename line
84
85Use C<~pattern> and C<!pattern> for positive and negative regexps.
a0d0e21e 86
4e1d3b43 87Nested data structures are printed out in a legible fashion, unlike
88the C<print> function.
89
90=item X [vars]
91
92Same as C<V currentpackage [vars]>.
a0d0e21e 93
94=item T
95
4e1d3b43 96Produce a stack backtrace. See below for details on its output.
a0d0e21e 97
4e1d3b43 98=item s [expr]
a0d0e21e 99
100Single step. Executes until it reaches the beginning of another
4e1d3b43 101statement, descending into subroutine calls. If an expression is
102supplied that includes function calls, it too will be single-stepped.
a0d0e21e 103
104=item n
105
106Next. Executes over subroutine calls, until it reaches the beginning
107of the next statement.
108
4e1d3b43 109=item <CR>
a0d0e21e 110
4e1d3b43 111Repeat last C<n> or C<s> command.
a0d0e21e 112
4e1d3b43 113=item c [line]
a0d0e21e 114
4e1d3b43 115Continue, optionally inserting a one-time-only breakpoint
116at the specified line.
a0d0e21e 117
4e1d3b43 118=item l
a0d0e21e 119
4e1d3b43 120List next window of lines.
a0d0e21e 121
122=item l min+incr
123
4e1d3b43 124List C<incr+1> lines starting at C<min>.
a0d0e21e 125
126=item l min-max
127
4e1d3b43 128List lines C<min> through C<max>.
a0d0e21e 129
130=item l line
131
4e1d3b43 132List a single line.
a0d0e21e 133
4e1d3b43 134=item l subname
a0d0e21e 135
4e1d3b43 136List first window of lines from subroutine.
a0d0e21e 137
138=item -
139
4e1d3b43 140List previous window of lines.
a0d0e21e 141
4e1d3b43 142=item w [line]
a0d0e21e 143
4e1d3b43 144List window (a few lines) around the current line.
a0d0e21e 145
4e1d3b43 146=item .
a0d0e21e 147
4e1d3b43 148Return debugger pointer to the last-executed line and
149print it out.
150
151=item f filename
152
153Switch to viewing a different file.
a0d0e21e 154
155=item /pattern/
156
4e1d3b43 157Search forwards for pattern; final / is optional.
a0d0e21e 158
159=item ?pattern?
160
4e1d3b43 161Search backwards for pattern; final ? is optional.
a0d0e21e 162
163=item L
164
4e1d3b43 165List all breakpoints and actions for the current file.
a0d0e21e 166
4e1d3b43 167=item S [[!]pattern]
a0d0e21e 168
4e1d3b43 169List subroutine names [not] matching pattern.
a0d0e21e 170
171=item t
172
4e1d3b43 173Toggle trace mode.
174
175=item t expr
176
177Trace through execution of expr. For example:
178
179 $ perl -de 42
180 Stack dump during die enabled outside of evals.
a0d0e21e 181
4e1d3b43 182 Loading DB routines from perl5db.pl patch level 0.94
183 Emacs support available.
184
185 Enter h or `h h' for help.
186
187 main::(-e:1): 0
188 DB<1> sub foo { 14 }
189
190 DB<2> sub bar { 3 }
191
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):
196 42
197 DB<4> q
198
199=item b [line] [condition]
a0d0e21e 200
201Set a breakpoint. If line is omitted, sets a breakpoint on the line
4e1d3b43 202that is about to be executed. If a condition is specified, it's
a0d0e21e 203evaluated each time the statement is reached and a breakpoint is taken
204only if the condition is true. Breakpoints may only be set on lines
4e1d3b43 205that begin an executable statement. Conditions don't use B<if>:
a0d0e21e 206
207 b 237 $x > 30
208 b 33 /pattern/i
209
4e1d3b43 210=item b subname [condition]
a0d0e21e 211
4e1d3b43 212Set a breakpoint at the first line of the named subroutine.
a0d0e21e 213
4e1d3b43 214=item d [line]
a0d0e21e 215
4e1d3b43 216Delete a breakpoint at the specified line. If line is omitted, deletes
217the breakpoint on the line that is about to be executed.
a0d0e21e 218
219=item D
220
4e1d3b43 221Delete all installed breakpoints.
222
223=item a [line] command
224
225Set an action to be done before the line is executed.
226The sequence of steps taken by the debugger is
227
228=over 3
229
230=item 1
231
232check for a breakpoint at this line
233
234=item 2
235
236print the line if necessary (tracing)
237
238=item 3
239
240do any actions associated with that line
241
242=item 4
243
244prompt user if at a breakpoint or in single-step
245
246=item 5
247
248evaluate line
249
250=back
a0d0e21e 251
4e1d3b43 252For example, this will print out C<$foo> every time line
25353 is passed:
a0d0e21e 254
4e1d3b43 255 a 53 print "DB FOUND $foo\n"
a0d0e21e 256
257=item A
258
4e1d3b43 259Delete all installed actions.
260
261=item O [opt[=val]] [opt"val"] [opt?]...
262
263Set or query values of options. val defaults to 1. opt can
264be abbreviated. Several options can be listed.
265
266=over 12
267
268=item recallCommand, ShellBang
269
270The characters used to recall command or spawn shell. By
271default, these are both set to C<!>.
272
273=item pager
274
275Program to use for output of pager-piped commands (those
276beginning with a C<|> character.) By default,
277C<$ENV{PAGER}> will be used.
278
279=back
280
281The following options affect what happens with C<V>, C<X>, and C<x>
282commands:
283
284=over 12
285
286=item arrayDepth, hashDepth
287
288Print only first N elements ('' for all).
289
290=item compactDump, veryCompact
291
292Change style of array and hash dump.
293
294=item globPrint
295
296Whether to print contents of globs.
297
298=item DumpDBFiles
299
300Dump arrays holding debugged files.
301
302=item DumpPackages
303
304Dump symbol tables of packages.
305
306=item quote, HighBit, undefPrint
307
308Change style of string dump.
309
310=item tkRunning
311
312Run Tk while prompting (with ReadLine).
313
314=item signalLevel, warnLevel. dieLevel
315
316Level of verbosity.
317
318=back
319
320The option C<PrintRet> affects printing of return value after C<r>
321command, The option C<frame> affects printing messages on entry and exit
322from subroutines. If C<frame> is 1, messages are printed on entry only;
323if it's set to more than that, they'll will be printed on exit as well,
324which may be useful if interdispersed with other messages.
325
326During startup options are initialized from $ENV{PERLDB_OPTS}.
327You can put additional initialization options C<TTY>, C<noTTY>,
328C<ReadLine>, and C<NonStop> there. Here's an example of using
329the C<$ENV{PERLDB_OPTS}> variable:
330
331 $ PERLDB_OPTS="N f=2" perl -d myprogram
332
333will run the script C<myprogram> without human intervention, printing
334out the call tree with entry and exit points. Note that C<N f=2> is
335equivalent to C<NonStop=1 frame=2>. Note also that at the moment when
336this documentation was written all the options to the debugger could
337be uniquely abbreviated by the first letter.
338
339See "Debugger Internals" below for more details.
a0d0e21e 340
341=item < command
342
343Set an action to happen before every debugger prompt. A multiline
344command may be entered by backslashing the newlines.
345
346=item > command
347
348Set an action to happen after the prompt when you've just given a
349command to return to executing the script. A multiline command may be
350entered by backslashing the newlines.
351
4e1d3b43 352=item ! number
a0d0e21e 353
4e1d3b43 354Redo a previous command (default previous command).
a0d0e21e 355
4e1d3b43 356=item ! -number
a0d0e21e 357
4e1d3b43 358Redo number'th-to-last command.
a0d0e21e 359
4e1d3b43 360=item ! pattern
a0d0e21e 361
4e1d3b43 362Redo last command that started with pattern.
363See C<O recallCommand>, too.
a0d0e21e 364
4e1d3b43 365=item !! cmd
a0d0e21e 366
4e1d3b43 367Run cmd in a subprocess (reads from DB::IN, writes to DB::OUT)
368See C<O shellBang> too.
a0d0e21e 369
370=item H -number
371
372Display last n commands. Only commands longer than one character are
373listed. If number is omitted, lists them all.
374
375=item q or ^D
376
377Quit. ("quit" doesn't work for this.)
378
4e1d3b43 379=item R
380
381Restart the debugger by B<exec>ing a new session. It tries to maintain
382your history across this, but internal settings and command line options
383may be lost.
384
385=item |dbcmd
386
387Run debugger command, piping DB::OUT to current pager.
388
389=item ||dbcmd
390
391Same as C<|dbcmd> but DB::OUT is temporarily B<select>ed as well.
392Often used with commands that would otherwise produce long
393output, such as
394
395 |V main
396
397=item = [alias value]
398
399Define a command alias, or list current aliases.
400
a0d0e21e 401=item command
402
403Execute command as a Perl statement. A missing semicolon will be
404supplied.
405
406=item p expr
407
408Same as C<print DB::OUT expr>. The DB::OUT filehandle is opened to
409/dev/tty, regardless of where STDOUT may be redirected to.
410
411=back
412
4e1d3b43 413The debugger prompt is something like
414
415 DB<8>
416
417or even
418
419 DB<<17>>
420
421where that number is the command number, which you'd use to access with
422the built-in B<csh>-like history mechanism, e.g. C<!17> would repeat
423command number 17. The number of angle brackets indicates the depth of
424the debugger. You could get more than one set of brackets, for example, if
425you'd already at a breakpoint and then printed out the result of a
426function call that itself also has a breakpoint.
427
428If you want to enter a multi-line command, such as a subroutine
429definition with several statements, you may escape the newline that would
430normally end the debugger command with a backslash. Here's an example:
a0d0e21e 431
4e1d3b43 432 DB<1> for (1..4) { \
433 cont: print "ok\n"; \
434 cont: }
435 ok
436 ok
437 ok
438 ok
439
440Note that this business of escaping a newline is specific to interactive
441commands typed into the debugger.
442
443Here's an example of what a stack backtrace might look like:
444
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
448
449The left-hand character up there tells whether the function was called
450in a scalar or list context (we bet you can tell which is which). What
451that says is that you were in the function C<main::infested> when you ran
452the stack dump, and that it was called in a scalar context from line 10
453of the file I<Ambulation.pm>, but without any arguments at all, meaning
454it was called as C<&infested>. The next stack frame shows that the
455function C<Ambulation::legs> was called in a list context from the
456I<camel_flea> file with four arguments. The last stack frame shows that
457C<main::pests> was called in a scalar context, also from I<camel_flea>,
458but from line 4.
459
460If you have any compile-time executable statements (code within a BEGIN
461block or a C<use> statement), these will C<NOT> be stopped by debugger,
462although C<require>s will. From your own Perl code, however, you can
463transfer control back to the debugger using the following statement,
464which is harmless if the debugger is not running:
a0d0e21e 465
466 $DB::single = 1;
467
4e1d3b43 468If you set C<$DB::single> to the value 2, it's equivalent to having
469just typed the C<n> command, whereas a value of 1 means the C<s>
470command. The C<$DB::trace> variable should be set to 1 to simulate
471having typed the C<t> command.
472
473=head2 Debugger Customization
a0d0e21e 474
475If you want to modify the debugger, copy F<perl5db.pl> from the Perl
476library to another name and modify it as necessary. You'll also want
4e1d3b43 477to set your PERL5DB environment variable to say something like this:
a0d0e21e 478
479 BEGIN { require "myperl5db.pl" }
480
481You can do some customization by setting up a F<.perldb> file which
482contains initialization code. For instance, you could make aliases
4e1d3b43 483like these (the last one is one people expect to be there):
a0d0e21e 484
4e1d3b43 485 $DB::alias{'len'} = 's/^len(.*)/p length($1)/';
a0d0e21e 486 $DB::alias{'stop'} = 's/^stop (at|in)/b/';
4e1d3b43 487 $DB::alias{'ps'} = 's/^ps\b/p scalar /';
488 $DB::alias{'quit'} = 's/^quit(\s*)/exit\$/';
489
490=head2 Readline Support
491
492As shipped, the only command line history supplied is a simplistic one
493that checks for leading exclamation points. However, if you install
494the Term::ReadKey and Term::ReadLine modules from CPAN, you will
495have full editing capabilities much like GNU I<readline>(3) provides.
496Look for these in the F<modules/by-module/Term> directory on CPAN.
497
498=head2 Editor Support for Debugging
499
500If you have GNU B<emacs> installed on your system, it can interact with
501the Perl debugger to provide an integrated software development
502environment reminiscent of its interactions with C debuggers.
503
504Perl is also delivered with a start file for making B<emacs> act like a
505syntax-directed editor that understands (some of) Perl's syntax. Look in
506the I<emacs> directory of the Perl source distribution.
507
508(Historically, a similar setup for interacting with B<vi> and the
509X11 window system had also been available, but at the time of this
510writing, no debugger support for B<vi> currently exists.)
511
512=head2 The Perl Profiler
513
514If you wish to supply an alternative debugger for Perl to run, just
515invoke your script with a colon and a package argument given to the B<-d>
516flag. One of the most popular alternative debuggers for Perl is
517B<DProf>, the Perl profiler. As of this writing, B<DProf> is not
518included with the standard Perl distribution, but it is expected to
519be included soon, for certain values of "soon".
520
521Meanwhile, you can fetch the Devel::Dprof module from CPAN. Assuming
522it's properly installed on your system, to profile your Perl program in
523the file F<mycode.pl>, just type:
524
525 perl -d:DProf mycode.pl
526
527When the script terminates the profiler will dump the profile information
528to a file called F<tmon.out>. A tool like B<dprofpp> (also supplied with
529the Devel::DProf package) can be used to interpret the information which is
530in that profile.
531
532=head2 Debugger Internals
533
534When you call the B<caller> function from package DB, Perl sets the
535C<@DB::args> array to contain the arguments that stack frame was called
536with. It also maintains other magical internal variables, such as
537C<@DB::dbline>, an array of the source code lines for the currently
538selected (with the debugger's C<f> command) file. Perl effectively
539inserts a call to the function C<DB::DB>(I<linenum>) in front of every
540place that can have a breakpoint. Instead of a subroutine call it calls
541C<DB::sub> setting C<$DB::sub> being the called subroutine. It also
542inserts a C<BEGIN {require 'perl5db.pl'}> before the first line.
543
544Note that no subroutine call is possible until C<&DB::sub> is defined
545(for subroutines defined outside this file). In fact, the same is
546true if C<$DB::deep> (how many levels of recursion deep into the
547debugger you are) is not defined.
a0d0e21e 548
4e1d3b43 549At the start, the debugger reads your rc file (F<./.perldb> or
550F<~/.perldb> under UNIX), which can set important options. This file may
551define a subroutine C<&afterinit> to be executed after the debugger is
552initialized.
553
554After the rc file is read, the debugger reads environment variable
555PERLDB_OPTS and parses it as a rest of C<O ...> line in debugger prompt.
556
557The following options can only be specified at startup. To set them in
558your rc file, call C<&parse_options("optionName=new_value")>.
559
560=over 12
561
562=item TTY
563
564The TTY to use for debugging I/O.
565
566=item noTTY
567
568If set, goes in C<NonStop> mode. On interrupt if TTY is not set uses the
569value of C<noTTY> or "/tmp/perldbtty$$" to find TTY using
570C<Term::Rendezvous>. Current variant is to have the name of TTY in this
571file.
572
573=item ReadLine
574
575If false, dummy ReadLine is used, so you can debug
576ReadLine applications.
577
578=item NonStop
579
580If true, no I/O is performed until an interrupt.
581
582=item LineInfo
583
584File or pipe to print line number info to. If it'sis a
585pipe, then a short, "emacs like" message is used.
586
587Example rc file:
588
589 &parse_options("NonStop=1 LineInfo=db.out");
590 sub afterinit { $trace = 1; }
591
592The script will run without human intervention, putting trace information
593into the file I<db.out>. (If you interrupt it, you would better reset
594C<LineInfo> to something "interactive"!)
595
596=back
a0d0e21e 597
598=head2 Other resources
599
600You did try the B<-w> switch, didn't you?
601
602=head1 BUGS
603
4e1d3b43 604If your program exit()s or die()s, so too does the debugger.
a0d0e21e 605
4e1d3b43 606You cannot get the stack frame information or otherwise debug functions
607that were not compiled by Perl, such as C or C++ extensions.
a0d0e21e 608
4e1d3b43 609If you alter your @_ arguments in a subroutine (such as with B<shift>
610or B<pop>, the stack backtrace will not show the original values.
a0d0e21e 611