1PERLDEBUG(1) Perl Programmers Reference Guide PERLDEBUG(1)
2
3
4
6 perldebug - Perl debugging
7
9 First of all, have you tried using "use strict;" and "use warnings;"?
10
11 If you're new to the Perl debugger, you may prefer to read perldebtut,
12 which is a tutorial introduction to the debugger.
13
14 If you're looking for the nitty gritty details of how the debugger is
15 implemented, you may prefer to read perldebguts.
16
17 For in-depth technical usage details, see perl5db.pl, the documentation
18 of the debugger itself.
19
21 If you invoke Perl with the -d switch, your script runs under the Perl
22 source debugger. This works like an interactive Perl environment,
23 prompting for debugger commands that let you examine source code, set
24 breakpoints, get stack backtraces, change the values of variables, etc.
25 This is so convenient that you often fire up the debugger all by itself
26 just to test out Perl constructs interactively to see what they do.
27 For example:
28
29 $ perl -d -e 42
30
31 In Perl, the debugger is not a separate program the way it usually is
32 in the typical compiled environment. Instead, the -d flag tells the
33 compiler to insert source information into the parse trees it's about
34 to hand off to the interpreter. That means your code must first
35 compile correctly for the debugger to work on it. Then when the
36 interpreter starts up, it preloads a special Perl library file
37 containing the debugger.
38
39 The program will halt right before the first run-time executable
40 statement (but see below regarding compile-time statements) and ask you
41 to enter a debugger command. Contrary to popular expectations,
42 whenever the debugger halts and shows you a line of code, it always
43 displays the line it's about to execute, rather than the one it has
44 just executed.
45
46 Any command not recognized by the debugger is directly executed
47 ("eval"'d) as Perl code in the current package. (The debugger uses the
48 DB package for keeping its own state information.)
49
50 Note that the said "eval" is bound by an implicit scope. As a result
51 any newly introduced lexical variable or any modified capture buffer
52 content is lost after the eval. The debugger is a nice environment to
53 learn Perl, but if you interactively experiment using material which
54 should be in the same scope, stuff it in one line.
55
56 For any text entered at the debugger prompt, leading and trailing
57 whitespace is first stripped before further processing. If a debugger
58 command coincides with some function in your own program, merely
59 precede the function with something that doesn't look like a debugger
60 command, such as a leading ";" or perhaps a "+", or by wrapping it with
61 parentheses or braces.
62
63 Calling the Debugger
64 There are several ways to call the debugger:
65
66 perl -d program_name
67 On the given program identified by "program_name".
68
69 perl -d -e 0
70 Interactively supply an arbitrary "expression" using "-e".
71
72 perl -d:ptkdb program_name
73 Debug a given program via the "Devel::ptkdb" GUI.
74
75 perl -dt threaded_program_name
76 Debug a given program using threads (experimental).
77
78 If Perl is called with the "-d" switch, the variable $^P will hold a
79 true value. This is useful if you need to know if your code is running
80 under the debugger:
81
82 if ( $^P ) {
83 # running under the debugger
84 }
85
86 See "$^P" in perlvar for more information on the variable.
87
88 Debugger Commands
89 The interactive debugger understands the following commands:
90
91 h Prints out a summary help message
92
93 h [command] Prints out a help message for the given debugger command.
94
95 h h The special argument of "h h" produces the entire help
96 page, which is quite long.
97
98 If the output of the "h h" command (or any command, for
99 that matter) scrolls past your screen, precede the command
100 with a leading pipe symbol so that it's run through your
101 pager, as in
102
103 DB> |h h
104
105 You may change the pager which is used via "o pager=..."
106 command.
107
108 p expr Same as "print {$DB::OUT} expr" in the current package. In
109 particular, because this is just Perl's own "print"
110 function, this means that nested data structures and
111 objects are not dumped, unlike with the "x" command.
112
113 The "DB::OUT" filehandle is opened to /dev/tty, regardless
114 of where STDOUT may be redirected to.
115
116 x [maxdepth] expr
117 Evaluates its expression in list context and dumps out the
118 result in a pretty-printed fashion. Nested data structures
119 are printed out recursively, unlike the real "print"
120 function in Perl. When dumping hashes, you'll probably
121 prefer 'x \%h' rather than 'x %h'. See Dumpvalue if you'd
122 like to do this yourself.
123
124 The output format is governed by multiple options described
125 under "Configurable Options".
126
127 If the "maxdepth" is included, it must be a numeral N; the
128 value is dumped only N levels deep, as if the "dumpDepth"
129 option had been temporarily set to N.
130
131 V [pkg [vars]]
132 Display all (or some) variables in package (defaulting to
133 "main") using a data pretty-printer (hashes show their keys
134 and values so you see what's what, control characters are
135 made printable, etc.). Make sure you don't put the type
136 specifier (like "$") there, just the symbol names, like
137 this:
138
139 V DB filename line
140
141 Use "~pattern" and "!pattern" for positive and negative
142 regexes.
143
144 This is similar to calling the "x" command on each
145 applicable var.
146
147 X [vars] Same as "V currentpackage [vars]".
148
149 y [level [vars]]
150 Display all (or some) lexical variables (mnemonic: "mY"
151 variables) in the current scope or level scopes higher.
152 You can limit the variables that you see with vars which
153 works exactly as it does for the "V" and "X" commands.
154 Requires the "PadWalker" module version 0.08 or higher;
155 will warn if this isn't installed. Output is pretty-
156 printed in the same style as for "V" and the format is
157 controlled by the same options.
158
159 T Produce a stack backtrace. See below for details on its
160 output.
161
162 s [expr] Single step. Executes until the beginning of another
163 statement, descending into subroutine calls. If an
164 expression is supplied that includes function calls, it too
165 will be single-stepped.
166
167 n [expr] Next. Executes over subroutine calls, until the beginning
168 of the next statement. If an expression is supplied that
169 includes function calls, those functions will be executed
170 with stops before each statement.
171
172 r Continue until the return from the current subroutine.
173 Dump the return value if the "PrintRet" option is set
174 (default).
175
176 <CR> Repeat last "n" or "s" command.
177
178 c [line|sub]
179 Continue, optionally inserting a one-time-only breakpoint
180 at the specified line or subroutine.
181
182 l List next window of lines.
183
184 l min+incr List "incr+1" lines starting at "min".
185
186 l min-max List lines "min" through "max". "l -" is synonymous to
187 "-".
188
189 l line List a single line.
190
191 l subname List first window of lines from subroutine. subname may be
192 a variable that contains a code reference.
193
194 - List previous window of lines.
195
196 v [line] View a few lines of code around the current line.
197
198 . Return the internal debugger pointer to the line last
199 executed, and print out that line.
200
201 f filename Switch to viewing a different file or "eval" statement. If
202 filename is not a full pathname found in the values of
203 %INC, it is considered a regex.
204
205 "eval"ed strings (when accessible) are considered to be
206 filenames: "f (eval 7)" and "f eval 7\b" access the body of
207 the 7th "eval"ed string (in the order of execution). The
208 bodies of the currently executed "eval" and of "eval"ed
209 strings that define subroutines are saved and thus
210 accessible.
211
212 /pattern/ Search forwards for pattern (a Perl regex); final / is
213 optional. The search is case-insensitive by default.
214
215 ?pattern? Search backwards for pattern; final ? is optional. The
216 search is case-insensitive by default.
217
218 L [abw] List (default all) actions, breakpoints and watch
219 expressions
220
221 S [[!]regex]
222 List subroutine names [not] matching the regex.
223
224 t [n] Toggle trace mode (see also the "AutoTrace" option).
225 Optional argument is the maximum number of levels to trace
226 below the current one; anything deeper than that will be
227 silent.
228
229 t [n] expr Trace through execution of "expr". Optional first argument
230 is the maximum number of levels to trace below the current
231 one; anything deeper than that will be silent. See "Frame
232 Listing Output Examples" in perldebguts for examples.
233
234 b Sets breakpoint on current line
235
236 b [line] [condition]
237 Set a breakpoint before the given line. If a condition is
238 specified, it's evaluated each time the statement is
239 reached: a breakpoint is taken only if the condition is
240 true. Breakpoints may only be set on lines that begin an
241 executable statement. Conditions don't use "if":
242
243 b 237 $x > 30
244 b 237 ++$count237 < 11
245 b 33 /pattern/i
246
247 If the line number is ".", sets a breakpoint on the current
248 line:
249
250 b . $n > 100
251
252 b [file]:[line] [condition]
253 Set a breakpoint before the given line in a (possibly
254 different) file. If a condition is specified, it's
255 evaluated each time the statement is reached: a breakpoint
256 is taken only if the condition is true. Breakpoints may
257 only be set on lines that begin an executable statement.
258 Conditions don't use "if":
259
260 b lib/MyModule.pm:237 $x > 30
261 b /usr/lib/perl5/site_perl/CGI.pm:100 ++$count100 < 11
262
263 b subname [condition]
264 Set a breakpoint before the first line of the named
265 subroutine. subname may be a variable containing a code
266 reference (in this case condition is not supported).
267
268 b postpone subname [condition]
269 Set a breakpoint at first line of subroutine after it is
270 compiled.
271
272 b load filename
273 Set a breakpoint before the first executed line of the
274 filename, which should be a full pathname found amongst the
275 %INC values.
276
277 b compile subname
278 Sets a breakpoint before the first statement executed after
279 the specified subroutine is compiled.
280
281 B line Delete a breakpoint from the specified line.
282
283 B * Delete all installed breakpoints.
284
285 disable [file]:[line]
286 Disable the breakpoint so it won't stop the execution of
287 the program. Breakpoints are enabled by default and can be
288 re-enabled using the "enable" command.
289
290 disable [line]
291 Disable the breakpoint so it won't stop the execution of
292 the program. Breakpoints are enabled by default and can be
293 re-enabled using the "enable" command.
294
295 This is done for a breakpoint in the current file.
296
297 enable [file]:[line]
298 Enable the breakpoint so it will stop the execution of the
299 program.
300
301 enable [line]
302 Enable the breakpoint so it will stop the execution of the
303 program.
304
305 This is done for a breakpoint in the current file.
306
307 a [line] command
308 Set an action to be done before the line is executed. If
309 line is omitted, set an action on the line about to be
310 executed. The sequence of steps taken by the debugger is
311
312 1. check for a breakpoint at this line
313 2. print the line if necessary (tracing)
314 3. do any actions associated with that line
315 4. prompt user if at a breakpoint or in single-step
316 5. evaluate line
317
318 For example, this will print out $foo every time line 53 is
319 passed:
320
321 a 53 print "DB FOUND $foo\n"
322
323 A line Delete an action from the specified line.
324
325 A * Delete all installed actions.
326
327 w expr Add a global watch-expression. Whenever a watched global
328 changes the debugger will stop and display the old and new
329 values.
330
331 W expr Delete watch-expression
332
333 W * Delete all watch-expressions.
334
335 o Display all options.
336
337 o booloption ...
338 Set each listed Boolean option to the value 1.
339
340 o anyoption? ...
341 Print out the value of one or more options.
342
343 o option=value ...
344 Set the value of one or more options. If the value has
345 internal whitespace, it should be quoted. For example, you
346 could set "o pager="less -MQeicsNfr"" to call less with
347 those specific options. You may use either single or
348 double quotes, but if you do, you must escape any embedded
349 instances of same sort of quote you began with, as well as
350 any escaping any escapes that immediately precede that
351 quote but which are not meant to escape the quote itself.
352 In other words, you follow single-quoting rules
353 irrespective of the quote; eg: "o option='this isn\'t bad'"
354 or "o option="She said, \"Isn't it?\""".
355
356 For historical reasons, the "=value" is optional, but
357 defaults to 1 only where it is safe to do so--that is,
358 mostly for Boolean options. It is always better to assign
359 a specific value using "=". The "option" can be
360 abbreviated, but for clarity probably should not be.
361 Several options can be set together. See "Configurable
362 Options" for a list of these.
363
364 < ? List out all pre-prompt Perl command actions.
365
366 < [ command ]
367 Set an action (Perl command) to happen before every
368 debugger prompt. A multi-line command may be entered by
369 backslashing the newlines.
370
371 < * Delete all pre-prompt Perl command actions.
372
373 << command Add an action (Perl command) to happen before every
374 debugger prompt. A multi-line command may be entered by
375 backwhacking the newlines.
376
377 > ? List out post-prompt Perl command actions.
378
379 > command Set an action (Perl command) to happen after the prompt
380 when you've just given a command to return to executing the
381 script. A multi-line command may be entered by
382 backslashing the newlines (we bet you couldn't have guessed
383 this by now).
384
385 > * Delete all post-prompt Perl command actions.
386
387 >> command Adds an action (Perl command) to happen after the prompt
388 when you've just given a command to return to executing the
389 script. A multi-line command may be entered by
390 backslashing the newlines.
391
392 { ? List out pre-prompt debugger commands.
393
394 { [ command ]
395 Set an action (debugger command) to happen before every
396 debugger prompt. A multi-line command may be entered in
397 the customary fashion.
398
399 Because this command is in some senses new, a warning is
400 issued if you appear to have accidentally entered a block
401 instead. If that's what you mean to do, write it as with
402 ";{ ... }" or even "do { ... }".
403
404 { * Delete all pre-prompt debugger commands.
405
406 {{ command Add an action (debugger command) to happen before every
407 debugger prompt. A multi-line command may be entered, if
408 you can guess how: see above.
409
410 ! number Redo a previous command (defaults to the previous command).
411
412 ! -number Redo number'th previous command.
413
414 ! pattern Redo last command that started with pattern. See "o
415 recallCommand", too.
416
417 !! cmd Run cmd in a subprocess (reads from DB::IN, writes to
418 DB::OUT) See "o shellBang", also. Note that the user's
419 current shell (well, their $ENV{SHELL} variable) will be
420 used, which can interfere with proper interpretation of
421 exit status or signal and coredump information.
422
423 source file Read and execute debugger commands from file. file may
424 itself contain "source" commands.
425
426 H -number Display last n commands. Only commands longer than one
427 character are listed. If number is omitted, list them all.
428
429 q or ^D Quit. ("quit" doesn't work for this, unless you've made an
430 alias) This is the only supported way to exit the debugger,
431 though typing "exit" twice might work.
432
433 Set the "inhibit_exit" option to 0 if you want to be able
434 to step off the end the script. You may also need to set
435 $finished to 0 if you want to step through global
436 destruction.
437
438 R Restart the debugger by "exec()"ing a new session. We try
439 to maintain your history across this, but internal settings
440 and command-line options may be lost.
441
442 The following setting are currently preserved: history,
443 breakpoints, actions, debugger options, and the Perl
444 command-line options -w, -I, and -e.
445
446 |dbcmd Run the debugger command, piping DB::OUT into your current
447 pager.
448
449 ||dbcmd Same as "|dbcmd" but DB::OUT is temporarily "select"ed as
450 well.
451
452 = [alias value]
453 Define a command alias, like
454
455 = quit q
456
457 or list current aliases.
458
459 command Execute command as a Perl statement. A trailing semicolon
460 will be supplied. If the Perl statement would otherwise be
461 confused for a Perl debugger, use a leading semicolon, too.
462
463 m expr List which methods may be called on the result of the
464 evaluated expression. The expression may evaluated to a
465 reference to a blessed object, or to a package name.
466
467 M Display all loaded modules and their versions.
468
469 man [manpage]
470 Despite its name, this calls your system's default
471 documentation viewer on the given page, or on the viewer
472 itself if manpage is omitted. If that viewer is man, the
473 current "Config" information is used to invoke man using
474 the proper MANPATH or -M manpath option. Failed lookups of
475 the form "XXX" that match known manpages of the form
476 perlXXX will be retried. This lets you type "man debug" or
477 "man op" from the debugger.
478
479 On systems traditionally bereft of a usable man command,
480 the debugger invokes perldoc. Occasionally this
481 determination is incorrect due to recalcitrant vendors or
482 rather more felicitously, to enterprising users. If you
483 fall into either category, just manually set the
484 $DB::doccmd variable to whatever viewer to view the Perl
485 documentation on your system. This may be set in an rc
486 file, or through direct assignment. We're still waiting
487 for a working example of something along the lines of:
488
489 $DB::doccmd = 'netscape -remote http://something.here/';
490
491 Configurable Options
492 The debugger has numerous options settable using the "o" command,
493 either interactively or from the environment or an rc file. The file is
494 named ./.perldb or ~/.perldb under Unix with /dev/tty, perldb.ini
495 otherwise.
496
497 "recallCommand", "ShellBang"
498 The characters used to recall a command or spawn a shell.
499 By default, both are set to "!", which is unfortunate.
500
501 "pager" Program to use for output of pager-piped commands (those
502 beginning with a "|" character.) By default, $ENV{PAGER}
503 will be used. Because the debugger uses your current
504 terminal characteristics for bold and underlining, if the
505 chosen pager does not pass escape sequences through
506 unchanged, the output of some debugger commands will not be
507 readable when sent through the pager.
508
509 "tkRunning" Run Tk while prompting (with ReadLine).
510
511 "signalLevel", "warnLevel", "dieLevel"
512 Level of verbosity. By default, the debugger leaves your
513 exceptions and warnings alone, because altering them can
514 break correctly running programs. It will attempt to print
515 a message when uncaught INT, BUS, or SEGV signals arrive.
516 (But see the mention of signals in "BUGS" below.)
517
518 To disable this default safe mode, set these values to
519 something higher than 0. At a level of 1, you get
520 backtraces upon receiving any kind of warning (this is
521 often annoying) or exception (this is often valuable).
522 Unfortunately, the debugger cannot discern fatal exceptions
523 from non-fatal ones. If "dieLevel" is even 1, then your
524 non-fatal exceptions are also traced and unceremoniously
525 altered if they came from "eval'ed" strings or from any
526 kind of "eval" within modules you're attempting to load.
527 If "dieLevel" is 2, the debugger doesn't care where they
528 came from: It usurps your exception handler and prints out
529 a trace, then modifies all exceptions with its own
530 embellishments. This may perhaps be useful for some
531 tracing purposes, but tends to hopelessly destroy any
532 program that takes its exception handling seriously.
533
534 "AutoTrace" Trace mode (similar to "t" command, but can be put into
535 "PERLDB_OPTS").
536
537 "LineInfo" File or pipe to print line number info to. If it is a pipe
538 (say, "|visual_perl_db"), then a short message is used.
539 This is the mechanism used to interact with a client editor
540 or visual debugger, such as the special "vi" or "emacs"
541 hooks, or the "ddd" graphical debugger.
542
543 "inhibit_exit"
544 If 0, allows stepping off the end of the script.
545
546 "PrintRet" Print return value after "r" command if set (default).
547
548 "ornaments" Affects screen appearance of the command line (see
549 Term::ReadLine). There is currently no way to disable
550 these, which can render some output illegible on some
551 displays, or with some pagers. This is considered a bug.
552
553 "frame" Affects the printing of messages upon entry and exit from
554 subroutines. If "frame & 2" is false, messages are printed
555 on entry only. (Printing on exit might be useful if
556 interspersed with other messages.)
557
558 If "frame & 4", arguments to functions are printed, plus
559 context and caller info. If "frame & 8", overloaded
560 "stringify" and "tie"d "FETCH" is enabled on the printed
561 arguments. If "frame & 16", the return value from the
562 subroutine is printed.
563
564 The length at which the argument list is truncated is
565 governed by the next option:
566
567 "maxTraceLen"
568 Length to truncate the argument list when the "frame"
569 option's bit 4 is set.
570
571 "windowSize"
572 Change the size of code list window (default is 10 lines).
573
574 The following options affect what happens with "V", "X", and "x"
575 commands:
576
577 "arrayDepth", "hashDepth"
578 Print only first N elements ('' for all).
579
580 "dumpDepth" Limit recursion depth to N levels when dumping structures.
581 Negative values are interpreted as infinity. Default:
582 infinity.
583
584 "compactDump", "veryCompact"
585 Change the style of array and hash output. If
586 "compactDump", short array may be printed on one line.
587
588 "globPrint" Whether to print contents of globs.
589
590 "DumpDBFiles"
591 Dump arrays holding debugged files.
592
593 "DumpPackages"
594 Dump symbol tables of packages.
595
596 "DumpReused"
597 Dump contents of "reused" addresses.
598
599 "quote", "HighBit", "undefPrint"
600 Change the style of string dump. The default value for
601 "quote" is "auto"; one can enable double-quotish or single-
602 quotish format by setting it to """ or "'", respectively.
603 By default, characters with their high bit set are printed
604 verbatim.
605
606 "UsageOnly" Rudimentary per-package memory usage dump. Calculates
607 total size of strings found in variables in the package.
608 This does not include lexicals in a module's file scope, or
609 lost in closures.
610
611 "HistFile" The path of the file from which the history (assuming a
612 usable Term::ReadLine backend) will be read on the
613 debugger's startup, and to which it will be saved on
614 shutdown (for persistence across sessions). Similar in
615 concept to Bash's ".bash_history" file.
616
617 "HistSize" The count of the saved lines in the history (assuming
618 "HistFile" above).
619
620 After the rc file is read, the debugger reads the $ENV{PERLDB_OPTS}
621 environment variable and parses this as the remainder of a "O ..."
622 line as one might enter at the debugger prompt. You may place the
623 initialization options "TTY", "noTTY", "ReadLine", and "NonStop" there.
624
625 If your rc file contains:
626
627 parse_options("NonStop=1 LineInfo=db.out AutoTrace");
628
629 then your script will run without human intervention, putting trace
630 information into the file db.out. (If you interrupt it, you'd better
631 reset "LineInfo" to /dev/tty if you expect to see anything.)
632
633 "TTY" The TTY to use for debugging I/O.
634
635 "noTTY" If set, the debugger goes into "NonStop" mode and will not
636 connect to a TTY. If interrupted (or if control goes to
637 the debugger via explicit setting of $DB::signal or
638 $DB::single from the Perl script), it connects to a TTY
639 specified in the "TTY" option at startup, or to a tty found
640 at runtime using the "Term::Rendezvous" module of your
641 choice.
642
643 This module should implement a method named "new" that
644 returns an object with two methods: "IN" and "OUT". These
645 should return filehandles to use for debugging input and
646 output correspondingly. The "new" method should inspect an
647 argument containing the value of $ENV{PERLDB_NOTTY} at
648 startup, or "$ENV{HOME}/.perldbtty$$" otherwise. This file
649 is not inspected for proper ownership, so security hazards
650 are theoretically possible.
651
652 "ReadLine" If false, readline support in the debugger is disabled in
653 order to debug applications that themselves use ReadLine.
654
655 "NonStop" If set, the debugger goes into non-interactive mode until
656 interrupted, or programmatically by setting $DB::signal or
657 $DB::single.
658
659 Here's an example of using the $ENV{PERLDB_OPTS} variable:
660
661 $ PERLDB_OPTS="NonStop frame=2" perl -d myprogram
662
663 That will run the script myprogram without human intervention, printing
664 out the call tree with entry and exit points. Note that "NonStop=1
665 frame=2" is equivalent to "N f=2", and that originally, options could
666 be uniquely abbreviated by the first letter (modulo the "Dump*"
667 options). It is nevertheless recommended that you always spell them
668 out in full for legibility and future compatibility.
669
670 Other examples include
671
672 $ PERLDB_OPTS="NonStop LineInfo=listing frame=2" perl -d myprogram
673
674 which runs script non-interactively, printing info on each entry into a
675 subroutine and each executed line into the file named listing. (If you
676 interrupt it, you would better reset "LineInfo" to something
677 "interactive"!)
678
679 Other examples include (using standard shell syntax to show environment
680 variable settings):
681
682 $ ( PERLDB_OPTS="NonStop frame=1 AutoTrace LineInfo=tperl.out"
683 perl -d myprogram )
684
685 which may be useful for debugging a program that uses "Term::ReadLine"
686 itself. Do not forget to detach your shell from the TTY in the window
687 that corresponds to /dev/ttyXX, say, by issuing a command like
688
689 $ sleep 1000000
690
691 See "Debugger Internals" in perldebguts for details.
692
693 Debugger Input/Output
694 Prompt The debugger prompt is something like
695
696 DB<8>
697
698 or even
699
700 DB<<17>>
701
702 where that number is the command number, and which you'd use to
703 access with the built-in csh-like history mechanism. For
704 example, "!17" would repeat command number 17. The depth of
705 the angle brackets indicates the nesting depth of the debugger.
706 You could get more than one set of brackets, for example, if
707 you'd already at a breakpoint and then printed the result of a
708 function call that itself has a breakpoint, or you step into an
709 expression via "s/n/t expression" command.
710
711 Multiline commands
712 If you want to enter a multi-line command, such as a subroutine
713 definition with several statements or a format, escape the
714 newline that would normally end the debugger command with a
715 backslash. Here's an example:
716
717 DB<1> for (1..4) { \
718 cont: print "ok\n"; \
719 cont: }
720 ok
721 ok
722 ok
723 ok
724
725 Note that this business of escaping a newline is specific to
726 interactive commands typed into the debugger.
727
728 Stack backtrace
729 Here's an example of what a stack backtrace via "T" command
730 might look like:
731
732 $ = main::infested called from file 'Ambulation.pm' line 10
733 @ = Ambulation::legs(1, 2, 3, 4) called from file 'camel_flea'
734 line 7
735 $ = main::pests('bactrian', 4) called from file 'camel_flea'
736 line 4
737
738 The left-hand character up there indicates the context in which
739 the function was called, with "$" and "@" meaning scalar or
740 list contexts respectively, and "." meaning void context (which
741 is actually a sort of scalar context). The display above says
742 that you were in the function "main::infested" when you ran the
743 stack dump, and that it was called in scalar context from line
744 10 of the file Ambulation.pm, but without any arguments at all,
745 meaning it was called as &infested. The next stack frame shows
746 that the function "Ambulation::legs" was called in list context
747 from the camel_flea file with four arguments. The last stack
748 frame shows that "main::pests" was called in scalar context,
749 also from camel_flea, but from line 4.
750
751 If you execute the "T" command from inside an active "use"
752 statement, the backtrace will contain both a "require" frame
753 and an "eval" frame.
754
755 Line Listing Format
756 This shows the sorts of output the "l" command can produce:
757
758 DB<<13>> l
759 101: @i{@i} = ();
760 102:b @isa{@i,$pack} = ()
761 103 if(exists $i{$prevpack} || exists $isa{$pack});
762 104 }
763 105
764 106 next
765 107==> if(exists $isa{$pack});
766 108
767 109:a if ($extra-- > 0) {
768 110: %isa = ($pack,1);
769
770 Breakable lines are marked with ":". Lines with breakpoints
771 are marked by "b" and those with actions by "a". The line
772 that's about to be executed is marked by "==>".
773
774 Please be aware that code in debugger listings may not look the
775 same as your original source code. Line directives and
776 external source filters can alter the code before Perl sees it,
777 causing code to move from its original positions or take on
778 entirely different forms.
779
780 Frame listing
781 When the "frame" option is set, the debugger would print
782 entered (and optionally exited) subroutines in different
783 styles. See perldebguts for incredibly long examples of these.
784
785 Debugging Compile-Time Statements
786 If you have compile-time executable statements (such as code within
787 BEGIN, UNITCHECK and CHECK blocks or "use" statements), these will not
788 be stopped by debugger, although "require"s and INIT blocks will, and
789 compile-time statements can be traced with the "AutoTrace" option set
790 in "PERLDB_OPTS"). From your own Perl code, however, you can transfer
791 control back to the debugger using the following statement, which is
792 harmless if the debugger is not running:
793
794 $DB::single = 1;
795
796 If you set $DB::single to 2, it's equivalent to having just typed the
797 "n" command, whereas a value of 1 means the "s" command. The
798 $DB::trace variable should be set to 1 to simulate having typed the
799 "t" command.
800
801 Another way to debug compile-time code is to start the debugger, set a
802 breakpoint on the load of some module:
803
804 DB<7> b load f:/perllib/lib/Carp.pm
805 Will stop on load of 'f:/perllib/lib/Carp.pm'.
806
807 and then restart the debugger using the "R" command (if possible). One
808 can use "b compile subname" for the same purpose.
809
810 Debugger Customization
811 The debugger probably contains enough configuration hooks that you
812 won't ever have to modify it yourself. You may change the behaviour of
813 the debugger from within the debugger using its "o" command, from the
814 command line via the "PERLDB_OPTS" environment variable, and from
815 customization files.
816
817 You can do some customization by setting up a .perldb file, which
818 contains initialization code. For instance, you could make aliases
819 like these (the last one is one people expect to be there):
820
821 $DB::alias{'len'} = 's/^len(.*)/p length($1)/';
822 $DB::alias{'stop'} = 's/^stop (at|in)/b/';
823 $DB::alias{'ps'} = 's/^ps\b/p scalar /';
824 $DB::alias{'quit'} = 's/^quit(\s*)/exit/';
825
826 You can change options from .perldb by using calls like this one;
827
828 parse_options("NonStop=1 LineInfo=db.out AutoTrace=1 frame=2");
829
830 The code is executed in the package "DB". Note that .perldb is
831 processed before processing "PERLDB_OPTS". If .perldb defines the
832 subroutine "afterinit", that function is called after debugger
833 initialization ends. .perldb may be contained in the current
834 directory, or in the home directory. Because this file is sourced in
835 by Perl and may contain arbitrary commands, for security reasons, it
836 must be owned by the superuser or the current user, and writable by no
837 one but its owner.
838
839 You can mock TTY input to debugger by adding arbitrary commands to
840 @DB::typeahead. For example, your .perldb file might contain:
841
842 sub afterinit { push @DB::typeahead, "b 4", "b 6"; }
843
844 Which would attempt to set breakpoints on lines 4 and 6 immediately
845 after debugger initialization. Note that @DB::typeahead is not a
846 supported interface and is subject to change in future releases.
847
848 If you want to modify the debugger, copy perl5db.pl from the Perl
849 library to another name and hack it to your heart's content. You'll
850 then want to set your "PERL5DB" environment variable to say something
851 like this:
852
853 BEGIN { require "myperl5db.pl" }
854
855 As a last resort, you could also use "PERL5DB" to customize the
856 debugger by directly setting internal variables or calling debugger
857 functions.
858
859 Note that any variables and functions that are not documented in this
860 document (or in perldebguts) are considered for internal use only, and
861 as such are subject to change without notice.
862
863 Readline Support / History in the Debugger
864 As shipped, the only command-line history supplied is a simplistic one
865 that checks for leading exclamation points. However, if you install
866 the Term::ReadKey and Term::ReadLine modules from CPAN (such as
867 Term::ReadLine::Gnu, Term::ReadLine::Perl, ...) you will have full
868 editing capabilities much like those GNU readline(3) provides. Look
869 for these in the modules/by-module/Term directory on CPAN. These do
870 not support normal vi command-line editing, however.
871
872 A rudimentary command-line completion is also available, including
873 lexical variables in the current scope if the "PadWalker" module is
874 installed.
875
876 Without Readline support you may see the symbols "^[[A", "^[[C",
877 "^[[B", "^[[D"", "^H", ... when using the arrow keys and/or the
878 backspace key.
879
880 Editor Support for Debugging
881 If you have the GNU's version of emacs installed on your system, it can
882 interact with the Perl debugger to provide an integrated software
883 development environment reminiscent of its interactions with C
884 debuggers.
885
886 Recent versions of Emacs come with a start file for making emacs act
887 like a syntax-directed editor that understands (some of) Perl's syntax.
888 See perlfaq3.
889
890 Users of vi should also look into vim and gvim, the mousey and windy
891 version, for coloring of Perl keywords.
892
893 Note that only perl can truly parse Perl, so all such CASE tools fall
894 somewhat short of the mark, especially if you don't program your Perl
895 as a C programmer might.
896
897 The Perl Profiler
898 If you wish to supply an alternative debugger for Perl to run, invoke
899 your script with a colon and a package argument given to the -d flag.
900 Perl's alternative debuggers include a Perl profiler, Devel::NYTProf,
901 which is available separately as a CPAN distribution. To profile your
902 Perl program in the file mycode.pl, just type:
903
904 $ perl -d:NYTProf mycode.pl
905
906 When the script terminates the profiler will create a database of the
907 profile information that you can turn into reports using the profiler's
908 tools. See <perlperf> for details.
909
911 "use re 'debug'" enables you to see the gory details of how the Perl
912 regular expression engine works. In order to understand this typically
913 voluminous output, one must not only have some idea about how regular
914 expression matching works in general, but also know how Perl's regular
915 expressions are internally compiled into an automaton. These matters
916 are explored in some detail in "Debugging Regular Expressions" in
917 perldebguts.
918
920 Perl contains internal support for reporting its own memory usage, but
921 this is a fairly advanced concept that requires some understanding of
922 how memory allocation works. See "Debugging Perl Memory Usage" in
923 perldebguts for the details.
924
926 You do have "use strict" and "use warnings" enabled, don't you?
927
928 perldebtut, perldebguts, perl5db.pl, re, DB, Devel::NYTProf, Dumpvalue,
929 and perlrun.
930
931 When debugging a script that uses #! and is thus normally found in
932 $PATH, the -S option causes perl to search $PATH for it, so you don't
933 have to type the path or "which $scriptname".
934
935 $ perl -Sd foo.pl
936
938 You cannot get stack frame information or in any fashion debug
939 functions that were not compiled by Perl, such as those from C or C++
940 extensions.
941
942 If you alter your @_ arguments in a subroutine (such as with "shift" or
943 "pop"), the stack backtrace will not show the original values.
944
945 The debugger does not currently work in conjunction with the -W
946 command-line switch, because it itself is not free of warnings.
947
948 If you're in a slow syscall (like "wait"ing, "accept"ing, or "read"ing
949 from your keyboard or a socket) and haven't set up your own $SIG{INT}
950 handler, then you won't be able to CTRL-C your way back to the
951 debugger, because the debugger's own $SIG{INT} handler doesn't
952 understand that it needs to raise an exception to longjmp(3) out of
953 slow syscalls.
954
955
956
957perl v5.36.0 2022-08-30 PERLDEBUG(1)