perlman
gods
<HR>
<P>
<H1><A NAME="NAME">NAME</A></H1>
<P>
perldebug - Perl debugging
<P>
<HR>
<H1><A NAME="DESCRIPTION">DESCRIPTION</A></H1>
<P>
First of all, have you tried using the <STRONG>-w</STRONG> switch?
<P>
<HR>
<H1><A NAME="The_Perl_Debugger">The Perl Debugger</A></H1>
<P>
``As soon as we started programming, we found to our surprise that it wasn't as easy to get programs right as we had thought. Debugging had to be discovered.
<FONT SIZE=-1>I</FONT> can remember the exact instant when
<FONT SIZE=-1>I</FONT> realized that a large part of my life from then on was going to be spent in finding mistakes in my own programs.''
<P>
<EM><PRE> --Maurice Wilkes, 1949
</PRE>
</EM>
<P>
If you invoke Perl with the <STRONG>-d</STRONG> switch, your script runs under the Perl source debugger. This works like an
interactive Perl environment, prompting 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:
<P>
<PRE> perl -d -e 42
</PRE>
<P>
In Perl, the debugger is not a separate program as it usually is in the
typical compiled environment. Instead, the <STRONG>-d</STRONG> flag tells the compiler to insert source information into the parse trees
it's about to hand off to the interpreter. That means your code must first
compile correctly for the debugger to work on it. Then when the interpreter
starts up, it preloads a Perl library file containing the debugger itself.
<P>
The program will halt <EM>right before</EM> the first run-time executable statement (but see below regarding
compile-time statements) and ask you to enter a debugger command. Contrary
to popular expectations, whenever the debugger halts and shows you a line
of code, it always displays the line it's <EM>about</EM> to execute, rather than the one it has just executed.
<P>
Any command not recognized by the debugger is directly executed ([perlfunc:eval|eval]'d) as Perl code in the current package. (The debugger uses the
<FONT SIZE=-1>DB</FONT> package for its own state information.)
<P>
Leading white space before a command would cause the debugger to think it's <EM>NOT</EM> a debugger command but for Perl, so be careful not to do that.
<P>
<HR>
<H2><A NAME="Debugger_Commands">Debugger Commands</A></H2>
<P>
The debugger understands the following commands:
<DL>
<DT><STRONG><A NAME="item_h">h [command]</A></STRONG><P>
<DD>
Prints out a help message.
<P>
If you supply another debugger command as an argument to the <CODE>h</CODE> command, it prints out the description for just that command. The special
argument of <CODE>h h</CODE> produces a more compact help listing, designed to fit together on one
screen.
<P>
If the output of the <CODE>h</CODE> command (or any command, for that matter) scrolls past your screen, either
precede the command with a leading pipe symbol so it's run through your
pager, as in
<P>
<PRE> DB> |h
</PRE>
<P>
You may change the pager which is used via <CODE>O pager=...</CODE> command.
<P><DT><STRONG><A NAME="item_p">p expr</A></STRONG><P>
<DD>
Same as <CODE>print {$DB::OUT} expr</CODE> in the current package. In particular, because this is just Perl's own <STRONG>print</STRONG> function, this means that nested data structures and objects are not
dumped, unlike with the <CODE>x</CODE> command.
<P>
The <CODE>DB::OUT</CODE> filehandle is opened to <EM>/dev/tty</EM>, regardless of where
<FONT SIZE=-1>STDOUT</FONT> may be redirected to.
<P><DT><STRONG><A NAME="item_x">x expr</A></STRONG><P>
<DD>
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 [perlfunc:print|print] function.
<P>
The details of printout are governed by multiple <CODE>O</CODE>ptions.
<P><DT><STRONG><A NAME="item_V">V [pkg [vars]]</A></STRONG><P>
<DD>
Display all (or some) variables in package (defaulting to the <CODE>main</CODE>
package) 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 <CODE>$</CODE>) there, just the symbol names, like this:
<P>
<PRE> V DB filename line
</PRE>
<P>
Use <CODE>~pattern</CODE> and <CODE>!pattern</CODE> for positive and negative regexps.
<P>
Nested data structures are printed out in a legible fashion, unlike the [perlfunc:print|print] function.
<P>
The details of printout are governed by multiple <CODE>O</CODE>ptions.
<P><DT><STRONG><A NAME="item_X">X [vars]</A></STRONG><P>
<DD>
Same as <CODE>V currentpackage [vars]</CODE>.
<P><DT><STRONG><A NAME="item_T">T</A></STRONG><P>
<DD>
Produce a stack backtrace. See below for details on its output.
<P><DT><STRONG><A NAME="item_s">s [expr]</A></STRONG><P>
<DD>
Single step. Executes until it reaches the beginning of another statement,
descending into subroutine calls. If an expression is supplied that
includes function calls, it too will be single-stepped.
<P><DT><STRONG><A NAME="item_n">n [expr]</A></STRONG><P>
<DD>
Next. Executes over subroutine calls, until it reaches 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.
<P><DT><STRONG><A NAME="item_ltCRgt">ltCRgt</A></STRONG><P>
<DD>
Repeat last <CODE>n</CODE> or [perlman:perlop] command.
<P><DT><STRONG><A NAME="item_c">c [line|sub]</A></STRONG><P>
<DD>
Continue, optionally inserting a one-time-only breakpoint at the specified
line or subroutine.
<P><DT><STRONG><A NAME="item_l">l</A></STRONG><P>
<DD>
List next window of lines.
<P><DT><STRONG>l min+incr</STRONG><P>
<DD>
List <CODE>incr+1</CODE> lines starting at <CODE>min</CODE>.
<P><DT><STRONG>l min-max</STRONG><P>
<DD>
List lines <CODE>min</CODE> through <CODE>max</CODE>. <CODE>l -</CODE> is synonymous to <CODE>-</CODE>.
<P><DT><STRONG>l line</STRONG><P>
<DD>
List a single line.
<P><DT><STRONG>l subname</STRONG><P>
<DD>
List first window of lines from subroutine.
<P><DT><STRONG><A NAME="item__">-</A></STRONG><P>
<DD>
List previous window of lines.
<P><DT><STRONG><A NAME="item_w">w [line]</A></STRONG><P>
<DD>
List window (a few lines) around the current line.
<P><DT><STRONG><A NAME="item__">.</A></STRONG><P>
<DD>
Return debugger pointer to the last-executed line and print it out.
<P><DT><STRONG><A NAME="item_f">f filename</A></STRONG><P>
<DD>
Switch to viewing a different file or eval statement. If <CODE>filename</CODE>
is not a full filename as found in values of
<FONT SIZE=-1>%INC,</FONT> it is considered as a regexp.
<P><DT><STRONG><A NAME="item__pattern_">/pattern/</A></STRONG><P>
<DD>
Search forwards for pattern; final / is optional.
<P><DT><STRONG><A NAME="item__pattern_">?pattern?</A></STRONG><P>
<DD>
Search backwards for pattern; final ? is optional.
<P><DT><STRONG><A NAME="item_L">L</A></STRONG><P>
<DD>
List all breakpoints and actions.
<P><DT><STRONG><A NAME="item_S">S [[!]pattern]</A></STRONG><P>
<DD>
List subroutine names [not] matching pattern.
<P><DT><STRONG><A NAME="item_t">t</A></STRONG><P>
<DD>
Toggle trace mode (see also <CODE>AutoTrace</CODE> <CODE>O</CODE>ption).
<P><DT><STRONG>t expr</STRONG><P>
<DD>
Trace through execution of expr. For example:
<P>
<PRE> $ perl -de 42
Stack dump during die enabled outside of evals.
</PRE>
<P>
<PRE> Loading DB routines from perl5db.pl patch level 0.94
Emacs support available.
</PRE>
<P>
<PRE> Enter h or `h h' for help.
</PRE>
<P>
<PRE> main::(-e:1): 0
DB<1> sub foo { 14 }
</PRE>
<P>
<PRE> DB<2> sub bar { 3 }
</PRE>
<P>
<PRE> DB<3> t print foo() * bar()
main::((eval 172):3): print foo() + bar();
main::foo((eval 168):2):
main::bar((eval 170):2):
42
</PRE>
<P>
or, with the <CODE>O</CODE>ption <CODE>frame=2</CODE> set,
<P>
<PRE> DB<4> O f=2
frame = '2'
DB<5> t print foo() * bar()
3: foo() * bar()
entering main::foo
2: sub foo { 14 };
exited main::foo
entering main::bar
2: sub bar { 3 };
exited main::bar
42
</PRE>
<DT><STRONG><A NAME="item_b">b [line] [condition]</A></STRONG><P>
<DD>
Set a breakpoint. If line is omitted, sets a breakpoint on the line that is
about to be executed. If a condition is specified, it's evaluated each time
the statement is reached and a breakpoint is taken only if the condition is
true. Breakpoints may be set on only lines that begin an executable
statement. Conditions don't use <STRONG>if</STRONG>:
<P>
<PRE> b 237 $x > 30
b 237 ++$count237 < 11
b 33 /pattern/i
</PRE>
<DT><STRONG>b subname [condition]</STRONG><P>
<DD>
Set a breakpoint at the first line of the named subroutine.
<P><DT><STRONG>b postpone subname [condition]</STRONG><P>
<DD>
Set breakpoint at first line of subroutine after it is compiled.
<P><DT><STRONG>b load filename</STRONG><P>
<DD>
Set breakpoint at the first executed line of the file. Filename should be a full name as found in values of
<FONT SIZE=-1>%INC.</FONT>
<P><DT><STRONG>b compile subname</STRONG><P>
<DD>
Sets breakpoint at the first statement executed after the subroutine is
compiled.
<P><DT><STRONG><A NAME="item_d">d [line]</A></STRONG><P>
<DD>
Delete a breakpoint at the specified line. If line is omitted, deletes the
breakpoint on the line that is about to be executed.
<P><DT><STRONG><A NAME="item_D">D</A></STRONG><P>
<DD>
Delete all installed breakpoints.
<P><DT><STRONG><A NAME="item_a">a [line] command</A></STRONG><P>
<DD>
Set an action to be done before the line is executed. The sequence of steps
taken by the debugger is
<P>
<PRE> 1. check for a breakpoint at this line
2. print the line if necessary (tracing)
3. do any actions associated with that line
4. prompt user if at a breakpoint or in single-step
5. evaluate line
</PRE>
<P>
For example, this will print out <CODE>$foo</CODE> every time line 53 is
passed:
<P>
<PRE> a 53 print "DB FOUND $foo\n"
</PRE>
<DT><STRONG><A NAME="item_A">A</A></STRONG><P>
<DD>
Delete all installed actions.
<P><DT><STRONG><A NAME="item_W">W [expr]</A></STRONG><P>
<DD>
Add a global watch-expression.
<P><DT><STRONG>W</STRONG><P>
<DD>
Delete all watch-expressions.
<P><DT><STRONG><A NAME="item_O">O [opt[=val]] [opt"val"] [opt?]...</A></STRONG><P>
<DD>
Set or query values of options. val defaults to 1. opt can be abbreviated.
Several options can be listed.
<DL>
<DT><STRONG><A NAME="item_recallCommand">recallCommand, ShellBang</A></STRONG><P>
<DD>
The characters used to recall command or spawn shell. By default, these are
both set to <CODE>!</CODE>.
<P><DT><STRONG><A NAME="item_pager">pager</A></STRONG><P>
<DD>
Program to use for output of pager-piped commands (those beginning with a <CODE>|</CODE> character.) By default,
<CODE>$ENV{PAGER}</CODE> will be used.
<P><DT><STRONG><A NAME="item_tkRunning">tkRunning</A></STRONG><P>
<DD>
Run Tk while prompting (with ReadLine).
<P><DT><STRONG><A NAME="item_signalLevel">signalLevel, warnLevel, dieLevel</A></STRONG><P>
<DD>
Level of verbosity. By default the debugger is in a sane verbose mode, thus
it will print backtraces on all the warnings and die-messages which are
going to be printed out, and will print a message when interesting uncaught
signals arrive.
<P>
To disable this behaviour, set these values to 0. If <CODE>dieLevel</CODE> is 2, then the messages which will be caught by surrounding [perlfunc:eval|eval] are also printed.
<P><DT><STRONG><A NAME="item_AutoTrace">AutoTrace</A></STRONG><P>
<DD>
Trace mode (similar to <CODE>t</CODE> command, but can be put into
<CODE>PERLDB_OPTS</CODE>).
<P><DT><STRONG><A NAME="item_LineInfo">LineInfo</A></STRONG><P>
<DD>
File or pipe to print line number info to. If it is a pipe (say,
<CODE>|visual_perl_db</CODE>), then a short, ``emacs like'' message is used.
<P><DT><STRONG><A NAME="item_inhibit_exit">inhibit_exit</A></STRONG><P>
<DD>
If 0, allows <EM>stepping off</EM> the end of the script.
<P><DT><STRONG><A NAME="item_PrintRet">PrintRet</A></STRONG><P>
<DD>
affects printing of return value after <CODE>r</CODE> command.
<P><DT><STRONG><A NAME="item_ornaments">ornaments</A></STRONG><P>
<DD>
affects screen appearance of the command line (see <EM>ReadLine</EM>).
<P><DT><STRONG><A NAME="item_frame">frame</A></STRONG><P>
<DD>
affects printing messages on entry and exit from subroutines. If
<CODE>frame & 2</CODE> is false, messages are printed on entry only. (Printing on exit may be useful if
<CODE>inter(di)spersed</CODE> with other messages.)
<P>
If <CODE>frame & 4</CODE>, arguments to functions are printed as well as the context and caller
info. If <CODE>frame & 8</CODE>, overloaded <CODE>stringify</CODE> and
[perlfunc:tie|tie]d <CODE>FETCH</CODE> are enabled on the printed arguments. If <CODE>frame &
16</CODE>, the return value from the subroutine is printed as well.
<P>
The length at which the argument list is truncated is governed by the next
option:
<P><DT><STRONG><A NAME="item_maxTraceLen">maxTraceLen</A></STRONG><P>
<DD>
length at which the argument list is truncated when <CODE>frame</CODE> option's bit 4 is set.
</DL>
<P>
The following options affect what happens with <CODE>V</CODE>, <CODE>X</CODE>, and <CODE>x</CODE>
commands:
<DL>
<DT><STRONG><A NAME="item_arrayDepth">arrayDepth, hashDepth</A></STRONG><P>
<DD>
Print only first
<FONT SIZE=-1>N</FONT> elements ('' for all).
<P><DT><STRONG><A NAME="item_compactDump">compactDump, veryCompact</A></STRONG><P>
<DD>
Change style of array and hash dump. If <CODE>compactDump</CODE>, short array may be printed on one line.
<P><DT><STRONG><A NAME="item_globPrint">globPrint</A></STRONG><P>
<DD>
Whether to print contents of globs.
<P><DT><STRONG><A NAME="item_DumpDBFiles">DumpDBFiles</A></STRONG><P>
<DD>
Dump arrays holding debugged files.
<P><DT><STRONG><A NAME="item_DumpPackages">DumpPackages</A></STRONG><P>
<DD>
Dump symbol tables of packages.
<P><DT><STRONG><A NAME="item_DumpReused">DumpReused</A></STRONG><P>
<DD>
Dump contents of ``reused'' addresses.
<P><DT><STRONG><A NAME="item_quote">quote, HighBit, undefPrint</A></STRONG><P>
<DD>
Change style of string dump. Default value of <CODE>quote</CODE> is <CODE>auto</CODE>, one can enable either double-quotish dump, or single-quotish by setting
it to <CODE>"</CODE> or <CODE>'</CODE>. By default, characters with high bit set are printed
<EM>as is</EM>.
<P><DT><STRONG><A NAME="item_UsageOnly">UsageOnly</A></STRONG><P>
<DD>
<EM>very</EM> rudimentally per-package memory usage dump. Calculates total size of
strings in variables in the package.
</DL>
<P>
During startup options are initialized from <CODE>$ENV{PERLDB_OPTS}</CODE>. You can put additional initialization options <CODE>TTY</CODE>, <CODE>noTTY</CODE>,
<CODE>ReadLine</CODE>, and <CODE>NonStop</CODE> there.
<P>
Example rc file:
<P>
<PRE> &parse_options("NonStop=1 LineInfo=db.out AutoTrace");
</PRE>
<P>
The script will run without human intervention, putting trace information
into the file <EM>db.out</EM>. (If you interrupt it, you would better reset
<CODE>LineInfo</CODE> to something ``interactive''!)
<DL>
<DT><STRONG><A NAME="item_TTY">TTY</A></STRONG><P>
<DD>
The
<FONT SIZE=-1>TTY</FONT> to use for debugging
<FONT SIZE=-1>I/O.</FONT>
<P><DT><STRONG><A NAME="item_noTTY">noTTY</A></STRONG><P>
<DD>
If set, goes in <CODE>NonStop</CODE> mode, and would not connect to a
<FONT SIZE=-1>TTY.</FONT> If interrupt (or if control goes to debugger via explicit setting of $DB::signal or $DB::single from the Perl script), connects to a
<FONT SIZE=-1>TTY</FONT> specified by the
<CODE>TTY</CODE> option at startup, or to a
<FONT SIZE=-1>TTY</FONT> found at runtime using <CODE>Term::Rendezvous</CODE> module of your choice.
<P>
This module should implement a method <CODE>new</CODE> which returns an object with two methods: <CODE>IN</CODE> and <CODE>OUT</CODE>, returning two filehandles to use for debugging input and output
correspondingly. Method <CODE>new</CODE> may inspect an argument which is a value of <CODE>$ENV{PERLDB_NOTTY}</CODE> at startup, or is <CODE>"/tmp/perldbtty$$"</CODE> otherwise.
<P><DT><STRONG><A NAME="item_ReadLine">ReadLine</A></STRONG><P>
<DD>
If false, readline support in debugger is disabled, so you can debug
ReadLine applications.
<P><DT><STRONG><A NAME="item_NonStop">NonStop</A></STRONG><P>
<DD>
If set, debugger goes into noninteractive mode until interrupted, or
programmatically by setting $DB::signal or $DB::single.
</DL>
<P>
Here's an example of using the <CODE>$ENV{PERLDB_OPTS}</CODE> variable:
<P>
<PRE> $ PERLDB_OPTS="N f=2" perl -d myprogram
</PRE>
<P>
will run the script <CODE>myprogram</CODE> without human intervention, printing out the call tree with entry and exit
points. Note that <CODE>N f=2</CODE> is equivalent to <CODE>NonStop=1 frame=2</CODE>. Note also that at the moment when this documentation was written all the
options to the debugger could be uniquely abbreviated by the first letter
(with exception of
<CODE>Dump*</CODE> options).
<P>
Other examples may include
<P>
<PRE> $ PERLDB_OPTS="N f A L=listing" perl -d myprogram
</PRE>
<P>
- runs script noninteractively, printing info on each entry into a
subroutine and each executed line into the file <EM>listing</EM>. (If you interrupt it, you would better reset <CODE>LineInfo</CODE> to something ``interactive''!)
<P>
<PRE> $ env "PERLDB_OPTS=R=0 TTY=/dev/ttyc" perl -d myprogram
</PRE>
<P>
may be useful for debugging a program which uses <CODE>Term::ReadLine</CODE>
itself. Do not forget detach shell from the
<FONT SIZE=-1>TTY</FONT> in the window which corresponds to <EM>/dev/ttyc</EM>, say, by issuing a command like
<P>
<PRE> $ sleep 1000000
</PRE>
<P>
See <A HREF="#Debugger_Internals">Debugger Internals</A> below for more details.
<P><DT><STRONG><A NAME="item_lt">lt [ command ]</A></STRONG><P>
<DD>
Set an action (Perl command) to happen before every debugger prompt.
<FONT SIZE=-1>A</FONT> multi-line command may be entered by backslashing
the newlines. If
<CODE>command</CODE> is missing, resets the list of actions.
<P><DT><STRONG><A NAME="item_ltlt">ltlt command</A></STRONG><P>
<DD>
Add an action (Perl command) to happen before every debugger prompt.
<FONT SIZE=-1>A</FONT> multi-line command may be entered by backslashing
the newlines.
<P><DT><STRONG><A NAME="item_gt">gt command</A></STRONG><P>
<DD>
Set an action (Perl command) to happen after the prompt when you've just given a command to return to executing the script.
<FONT SIZE=-1>A</FONT> multi-line command may be entered by backslashing the newlines. If
<CODE>command</CODE> is missing, resets the list of actions.
<P><DT><STRONG><A NAME="item_gtgt">gtgt command</A></STRONG><P>
<DD>
Adds an action (Perl command) to happen after the prompt when you've just given a command to return to executing the script.
<FONT SIZE=-1>A</FONT> multi-line command may be entered by backslashing the newlines.
<P><DT><STRONG><A NAME="item__">{ [ command ]</A></STRONG><P>
<DD>
Set an action (debugger command) to happen before every debugger prompt.
<FONT SIZE=-1>A</FONT> multi-line command may be entered by backslashing
the newlines. If
<CODE>command</CODE> is missing, resets the list of actions.
<P><DT><STRONG><A NAME="item__">{{ command</A></STRONG><P>
<DD>
Add an action (debugger command) to happen before every debugger prompt.
<FONT SIZE=-1>A</FONT> multi-line command may be entered by backslashing
the newlines.
<P><DT><STRONG><A NAME="item__">! number</A></STRONG><P>
<DD>
Redo a previous command (default previous command).
<P><DT><STRONG>! -number</STRONG><P>
<DD>
Redo number'th-to-last command.
<P><DT><STRONG>! pattern</STRONG><P>
<DD>
Redo last command that started with pattern. See <CODE>O recallCommand</CODE>, too.
<P><DT><STRONG><A NAME="item__">!! cmd</A></STRONG><P>
<DD>
Run cmd in a subprocess (reads from
<FONT SIZE=-1>DB::IN,</FONT> writes to
<FONT SIZE=-1>DB::OUT)</FONT> See
<CODE>O shellBang</CODE> too.
<P><DT><STRONG><A NAME="item_H">H -number</A></STRONG><P>
<DD>
Display last n commands. Only commands longer than one character are
listed. If number is omitted, lists them all.
<P><DT><STRONG><A NAME="item_q">q or ^D</A></STRONG><P>
<DD>
Quit. (``quit'' doesn't work for this.) This is the only supported way to
exit the debugger, though typing [perlfunc:exit|exit] twice may do it too.
<P>
Set an <CODE>O</CODE>ption <CODE>inhibit_exit</CODE> to 0 if you want to be able to <EM>step
off</EM> the end the script. You may also need to set <CODE>$finished</CODE> to 0 at some moment if you want to step through global destruction.
<P><DT><STRONG><A NAME="item_R">R</A></STRONG><P>
<DD>
Restart the debugger by <STRONG>exec</STRONG>ing a new session. It tries to maintain your history across this, but
internal settings and command line options may be lost.
<P>
Currently the following setting are preserved: history, breakpoints,
actions, debugger <CODE>O</CODE>ptions, and the following command line options: <STRONG>-w</STRONG>, <STRONG>-I</STRONG>, and <STRONG>-e</STRONG>.
<P><DT><STRONG><A NAME="item__dbcmd">|dbcmd</A></STRONG><P>
<DD>
Run debugger command, piping
<FONT SIZE=-1>DB::OUT</FONT> to current pager.
<P><DT><STRONG><A NAME="item__dbcmd">||dbcmd</A></STRONG><P>
<DD>
Same as <CODE>|dbcmd</CODE> but
<FONT SIZE=-1>DB::OUT</FONT> is temporarily <STRONG>select</STRONG>ed as well. Often used with commands that would otherwise produce long
output, such as
<P>
<PRE> |V main
</PRE>
<DT><STRONG><A NAME="item__">= [alias value]</A></STRONG><P>
<DD>
Define a command alias, like
<P>
<PRE> = quit q
</PRE>
<P>
or list current aliases.
<P><DT><STRONG><A NAME="item_command">command</A></STRONG><P>
<DD>
Execute command as a Perl statement.
<FONT SIZE=-1>A</FONT> missing semicolon will be supplied.
<P><DT><STRONG><A NAME="item_m">m expr</A></STRONG><P>
<DD>
The expression is evaluated, and the methods which may be applied to the
result are listed.
<P><DT><STRONG>m package</STRONG><P>
<DD>
The methods which may be applied to objects in the [perlfunc:package|package] are listed.
</DL>
<P>
<HR>
<H2><A NAME="Debugger_input_output">Debugger input/output</A></H2>
<DL>
<DT><STRONG><A NAME="item_Prompt">Prompt</A></STRONG><P>
<DD>
The debugger prompt is something like
<P>
<PRE> DB<8>
</PRE>
<P>
or even
<P>
<PRE> DB<<17>>
</PRE>
<P>
where that number is the command number, which you'd use to access with the
builtin <STRONG>csh</STRONG>-like history mechanism, e.g., <CODE>!17</CODE> would repeat command number 17. The number of angle brackets indicates the
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 out the result
of a function call that itself also has a breakpoint, or you step into an
expression via <CODE>s/n/t expression</CODE> command.
<P><DT><STRONG><A NAME="item_Multiline">Multiline commands</A></STRONG><P>
<DD>
If you want to enter a multi-line command, such as a subroutine definition
with several statements, or a format, you may escape the newline that would
normally end the debugger command with a backslash. Here's an example:
<P>
<PRE> DB<1> for (1..4) { \
cont: print "ok\n"; \
cont: }
ok
ok
ok
ok
</PRE>
<P>
Note that this business of escaping a newline is specific to interactive
commands typed into the debugger.
<P><DT><STRONG><A NAME="item_Stack">Stack backtrace</A></STRONG><P>
<DD>
Here's an example of what a stack backtrace via <CODE>T</CODE> command might look like:
<P>
<PRE> $ = 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
</PRE>
<P>
The left-hand character up there tells whether the function was called in a
scalar or list context (we bet you can tell which is which). What that says
is that you were in the function <CODE>main::infested</CODE> when you ran the stack dump, and that it was called in a scalar context
from line 10 of the file <EM>Ambulation.pm</EM>, but without any arguments at all, meaning it was called as <CODE>&infested</CODE>. The next stack frame shows that the function <CODE>Ambulation::legs</CODE> was called in a list context from the
<EM>camel_flea</EM> file with four arguments. The last stack frame shows that
<CODE>main::pests</CODE> was called in a scalar context, also from <EM>camel_flea</EM>, but from line 4.
<P>
Note that if you execute <CODE>T</CODE> command from inside an active [perlfunc:use|use]
statement, the backtrace will contain both [perlfunc:require|require]
frame and an [perlfunc:eval|eval]) frame.
<P><DT><STRONG><A NAME="item_Listing">Listing</A></STRONG><P>
<DD>
Listing given via different flavors of <CODE>l</CODE> command looks like this:
<P>
<PRE> 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);
</PRE>
<P>
Note that the breakable lines are marked with <CODE>:</CODE>, lines with breakpoints are marked by <CODE>b</CODE>, with actions by <CODE>a</CODE>, and the next executed line is marked by <CODE>==></CODE>.
<P><DT><STRONG><A NAME="item_Frame">Frame listing</A></STRONG><P>
<DD>
When <CODE>frame</CODE> option is set, debugger would print entered (and optionally exited)
subroutines in different styles.
<P>
What follows is the start of the listing of
<P>
<PRE> env "PERLDB_OPTS=f=n N" perl -d -V
</PRE>
<P>
for different values of <CODE>n</CODE>:
<OL>
<LI>
<P>
<PRE> entering main::BEGIN
entering Config::BEGIN
Package lib/Exporter.pm.
Package lib/Carp.pm.
Package lib/Config.pm.
entering Config::TIEHASH
entering Exporter::import
entering Exporter::export
entering Config::myconfig
entering Config::FETCH
entering Config::FETCH
entering Config::FETCH
entering Config::FETCH
</PRE>
<LI>
<P>
<PRE> entering main::BEGIN
entering Config::BEGIN
Package lib/Exporter.pm.
Package lib/Carp.pm.
exited Config::BEGIN
Package lib/Config.pm.
entering Config::TIEHASH
exited Config::TIEHASH
entering Exporter::import
entering Exporter::export
exited Exporter::export
exited Exporter::import
exited main::BEGIN
entering Config::myconfig
entering Config::FETCH
exited Config::FETCH
entering Config::FETCH
exited Config::FETCH
entering Config::FETCH
</PRE>
<LI>
<P>
<PRE> in $=main::BEGIN() from /dev/nul:0
in $=Config::BEGIN() from lib/Config.pm:2
Package lib/Exporter.pm.
Package lib/Carp.pm.
Package lib/Config.pm.
in $=Config::TIEHASH('Config') from lib/Config.pm:644
in $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/nul:0
in $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from li
in @=Config::myconfig() from /dev/nul:0
in $=Config::FETCH(ref(Config), 'package') from lib/Config.pm:574
in $=Config::FETCH(ref(Config), 'baserev') from lib/Config.pm:574
in $=Config::FETCH(ref(Config), 'PATCHLEVEL') from lib/Config.pm:574
in $=Config::FETCH(ref(Config), 'SUBVERSION') from lib/Config.pm:574
in $=Config::FETCH(ref(Config), 'osname') from lib/Config.pm:574
in $=Config::FETCH(ref(Config), 'osvers') from lib/Config.pm:574
</PRE>
<LI>
<P>
<PRE> in $=main::BEGIN() from /dev/nul:0
in $=Config::BEGIN() from lib/Config.pm:2
Package lib/Exporter.pm.
Package lib/Carp.pm.
out $=Config::BEGIN() from lib/Config.pm:0
Package lib/Config.pm.
in $=Config::TIEHASH('Config') from lib/Config.pm:644
out $=Config::TIEHASH('Config') from lib/Config.pm:644
in $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/nul:0
in $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/
out $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/
out $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/nul:0
out $=main::BEGIN() from /dev/nul:0
in @=Config::myconfig() from /dev/nul:0
in $=Config::FETCH(ref(Config), 'package') from lib/Config.pm:574
out $=Config::FETCH(ref(Config), 'package') from lib/Config.pm:574
in $=Config::FETCH(ref(Config), 'baserev') from lib/Config.pm:574
out $=Config::FETCH(ref(Config), 'baserev') from lib/Config.pm:574
in $=Config::FETCH(ref(Config), 'PATCHLEVEL') from lib/Config.pm:574
out $=Config::FETCH(ref(Config), 'PATCHLEVEL') from lib/Config.pm:574
in $=Config::FETCH(ref(Config), 'SUBVERSION') from lib/Config.pm:574
</PRE>
<LI><STRONG><A NAME="item_4">4</A></STRONG>
<P>
<PRE> in $=main::BEGIN() from /dev/nul:0
in $=Config::BEGIN() from lib/Config.pm:2
Package lib/Exporter.pm.
Package lib/Carp.pm.
out $=Config::BEGIN() from lib/Config.pm:0
Package lib/Config.pm.
in $=Config::TIEHASH('Config') from lib/Config.pm:644
out $=Config::TIEHASH('Config') from lib/Config.pm:644
in $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/nul:0
in $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/E
out $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/E
out $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/nul:0
out $=main::BEGIN() from /dev/nul:0
in @=Config::myconfig() from /dev/nul:0
in $=Config::FETCH('Config=HASH(0x1aa444)', 'package') from lib/Config.pm:574
out $=Config::FETCH('Config=HASH(0x1aa444)', 'package') from lib/Config.pm:574
in $=Config::FETCH('Config=HASH(0x1aa444)', 'baserev') from lib/Config.pm:574
out $=Config::FETCH('Config=HASH(0x1aa444)', 'baserev') from lib/Config.pm:574
</PRE>
<LI><STRONG><A NAME="item_0">0</A></STRONG>
<P>
<PRE> in $=CODE(0x15eca4)() from /dev/null:0
in $=CODE(0x182528)() from lib/Config.pm:2
Package lib/Exporter.pm.
out $=CODE(0x182528)() from lib/Config.pm:0
scalar context return from CODE(0x182528): undef
Package lib/Config.pm.
in $=Config::TIEHASH('Config') from lib/Config.pm:628
out $=Config::TIEHASH('Config') from lib/Config.pm:628
scalar context return from Config::TIEHASH: empty hash
in $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0
in $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/Exporter.pm:171
out $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/Exporter.pm:171
scalar context return from Exporter::export: ''
out $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0
scalar context return from Exporter::import: ''
</PRE>
</OL>
<P>
In all the cases indentation of lines shows the call tree, if bit 2 of
<CODE>frame</CODE> is set, then a line is printed on exit from a subroutine as well, if bit 4
is set, then the arguments are printed as well as the caller info, if bit 8
is set, the arguments are printed even if they are tied or references, if
bit 16 is set, the return value is printed as well.
<P>
When a package is compiled, a line like this
<P>
<PRE> Package lib/Carp.pm.
</PRE>
<P>
is printed with proper indentation.
</DL>
<P>
<HR>
<H2><A NAME="Debugging_compile_time_statement">Debugging compile-time statements</A></H2>
<P>
If you have any compile-time executable statements (code within a
<FONT SIZE=-1>BEGIN</FONT> block or a [perlfunc:use|use] statement), these will <CODE>NOT</CODE> be stopped by debugger, although [perlfunc:require|require]s will (and compile-time statements can be traced with <CODE>AutoTrace</CODE> option set in <CODE>PERLDB_OPTS</CODE>). From your own Perl code, however, you can transfer control back to the
debugger using the following statement, which is harmless if the debugger
is not running:
<P>
<PRE> $DB::single = 1;
</PRE>
<P>
If you set <CODE>$DB::single</CODE> to the value 2, it's equivalent to having just typed the <CODE>n</CODE> command, whereas a value of 1 means the [perlman:perlop]
command. The <CODE>$DB::trace</CODE> variable should be set to 1 to simulate having typed the <CODE>t</CODE> command.
<P>
Another way to debug compile-time code is to start debugger, set a
breakpoint on <EM>load</EM> of some module thusly
<P>
<PRE> DB<7> b load f:/perllib/lib/Carp.pm
Will stop on load of `f:/perllib/lib/Carp.pm'.
</PRE>
<P>
and restart debugger by <CODE>R</CODE> command (if possible). One can use <CODE>b
compile subname</CODE> for the same purpose.
<P>
<HR>
<H2><A NAME="Debugger_Customization">Debugger Customization</A></H2>
<P>
Most probably you do not want to modify the debugger, it contains enough
hooks to satisfy most needs. You may change the behaviour of debugger from
the debugger itself, using <CODE>O</CODE>ptions, from the command line via
<CODE>PERLDB_OPTS</CODE> environment variable, and from <EM>customization files</EM>.
<P>
You can do some customization by setting up a <EM>.perldb</EM> file which contains initialization code. For instance, you could make
aliases like these (the last one is one people expect to be there):
<P>
<PRE> $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\$/';
</PRE>
<P>
One changes options from <EM>.perldb</EM> file via calls like this one;
<P>
<PRE> parse_options("NonStop=1 LineInfo=db.out AutoTrace=1 frame=2");
</PRE>
<P>
(the code is executed in the package <CODE>DB</CODE>). Note that <EM>.perldb</EM> is processed before processing <CODE>PERLDB_OPTS</CODE>. If <EM>.perldb</EM> defines the subroutine <CODE>afterinit</CODE>, it is called after all the debugger initialization ends. <EM>.perldb</EM> may be contained in the current directory, or in the [perlman:perlrun]/[perlman:perlrun] directory.
<P>
If you want to modify the debugger, copy <EM>perl5db.pl</EM> from the Perl library to another name and modify it as necessary. You'll
also want to set your [perlman:perlrun] environment variable to say something like this:
<P>
<PRE> BEGIN { require "myperl5db.pl" }
</PRE>
<P>
As the last resort, one can use [perlman:perlrun] to customize debugger by directly setting internal variables or calling
debugger functions.
<P>
<HR>
<H2><A NAME="Readline_Support">Readline Support</A></H2>
<P>
As shipped, the only command line history supplied is a simplistic one that checks for leading exclamation points. However, if you install the Term::ReadKey and Term::ReadLine modules from
<FONT SIZE=-1>CPAN,</FONT> you will have full editing capabilities much like
<FONT SIZE=-1>GNU</FONT>
<EM>readline</EM>(3) provides. Look for these in the <EM>modules/by-module/Term</EM> directory on
<FONT SIZE=-1>CPAN.</FONT>
<P>
<FONT SIZE=-1>A</FONT> rudimentary command line completion is also
available. Unfortunately, the names of lexical variables are not available
for completion.
<P>
<HR>
<H2><A NAME="Editor_Support_for_Debugging">Editor Support for Debugging</A></H2>
<P>
If you have
<FONT SIZE=-1>GNU</FONT> <STRONG>emacs</STRONG> installed on your system, it can interact with the Perl debugger to provide an integrated software development environment reminiscent of its interactions with
<FONT SIZE=-1>C</FONT> debuggers.
<P>
Perl is also delivered with a start file for making <STRONG>emacs</STRONG> act like a syntax-directed editor that understands (some of) Perl's syntax.
Look in the <EM>emacs</EM> directory of the Perl source distribution.
<P>
(Historically, a similar setup for interacting with <STRONG>vi</STRONG> and the
<FONT SIZE=-1>X11</FONT> window system had also been available, but at the
time of this writing, no debugger support for <STRONG>vi</STRONG> currently exists.)
<P>
<HR>
<H2><A NAME="The_Perl_Profiler">The Perl Profiler</A></H2>
<P>
If you wish to supply an alternative debugger for Perl to run, just invoke
your script with a colon and a package argument given to the <STRONG>-d</STRONG>
flag. One of the most popular alternative debuggers for Perl is
<STRONG>DProf</STRONG>, the Perl profiler. As of this writing, <STRONG>DProf</STRONG> is not included with the standard Perl distribution, but it is expected to
be included soon, for certain values of ``soon''.
<P>
Meanwhile, you can fetch the Devel::Dprof module from
<FONT SIZE=-1>CPAN.</FONT> Assuming it's properly installed on your system,
to profile your Perl program in the file <EM>mycode.pl</EM>, just type:
<P>
<PRE> perl -d:DProf mycode.pl
</PRE>
<P>
When the script terminates the profiler will dump the profile information
to a file called <EM>tmon.out</EM>.
<FONT SIZE=-1>A</FONT> tool like <STRONG>dprofpp</STRONG> (also supplied with the Devel::DProf package) can be used to interpret the
information which is in that profile.
<P>
<HR>
<H2><A NAME="Debugger_support_in_perl">Debugger support in perl</A></H2>
<P>
When you call the <STRONG>caller</STRONG> function (see [perlfunc:caller|caller]) from the package
<FONT SIZE=-1>DB,</FONT> Perl sets the array @DB::args to contain the
arguments the corresponding stack frame was called with.
<P>
If perl is run with <STRONG>-d</STRONG> option, the following additional features are enabled (cf. [perlman:perlvar]):
<UL>
<LI>
<P>
Perl inserts the contents of <CODE>$ENV{PERL5DB}</CODE> (or <CODE>BEGIN {require
'perl5db.pl'}</CODE> if not present) before the first line of the application.
<P><LI>
The array <CODE>@{"_<$filename"}</CODE> is the line-by-line contents of <CODE>$filename</CODE> for all the compiled
files. Same for [perlfunc:eval|eval]ed strings which contain subroutines, or which are currently executed. The <CODE>$filename</CODE>
for [perlfunc:eval|eval]ed strings looks like <CODE>(eval 34)</CODE>.
<P><LI>
The hash <CODE>%{"_<$filename"}</CODE> contains breakpoints and action (it is keyed by line number), and
individual entries are settable (as opposed to the whole hash). Only
true/false is important to Perl, though the values used by <EM>perl5db.pl</EM> have the form
<CODE>"$break_condition\0$action"</CODE>. Values are magical in numeric context: they are zeros if the line is not
breakable.
<P>
Same for evaluated strings which contain subroutines, or which are
currently executed. The <CODE>$filename</CODE> for [perlfunc:eval|eval]ed strings looks like
<CODE>(eval 34)</CODE>.
<P><LI>
The scalar <CODE>${"_<$filename"}</CODE> contains <CODE>"_<$filename"</CODE>. Same for evaluated strings which contain subroutines, or which are
currently executed. The <CODE>$filename</CODE> for [perlfunc:eval|eval]ed strings looks like <CODE>(eval
34)</CODE>.
<P><LI>
After each [perlfunc:require|require]d file is compiled, but before it is executed,
<CODE>DB::postponed(*{"_<$filename"})</CODE> is called (if subroutine
<CODE>DB::postponed</CODE> exists). Here the <CODE>$filename</CODE> is the expanded name of the [perlfunc:require|require]d file (as found in values of
<FONT SIZE=-1>%INC).</FONT>
<P><LI>
After each subroutine <CODE>subname</CODE> is compiled existence of
<CODE>$DB::postponed{subname}</CODE> is checked. If this key exists,
<CODE>DB::postponed(subname)</CODE> is called (if subroutine <CODE>DB::postponed</CODE>
exists).
<P><LI>
<FONT SIZE=-1>A</FONT> hash <CODE>%DB::sub</CODE> is maintained, with keys being subroutine names, values having the form <CODE>filename:startline-endline</CODE>. <CODE>filename</CODE> has the form <CODE>(eval 31)</CODE> for subroutines defined inside [perlfunc:eval|eval]s.
<P><LI>
When execution of the application reaches a place that can have a
breakpoint, a call to <CODE>DB::DB()</CODE> is performed if any one of variables $DB::trace, $DB::single, or
$DB::signal is true. (Note that these variables are not [perlfunc:local|local]izable.) This feature is disabled when the control is inside <CODE>DB::DB()</CODE> or functions called from it (unless
<CODE>$^D & (1<<30)</CODE>).
<P><LI>
When execution of the application reaches a subroutine call, a call to <CODE>&DB::sub</CODE>(<EM>args</EM>) is performed instead, with <CODE>$DB::sub</CODE> being the name of the called subroutine. (Unless the subroutine is compiled
in the package <CODE>DB</CODE>.)
</UL>
<P>
Note that if <CODE>&DB::sub</CODE> needs some external data to be setup for it to work, no subroutine call is
possible until this is done. For the standard debugger <CODE>$DB::deep</CODE> (how many levels of recursion deep into the debugger you can go before a
mandatory break) gives an example of such a dependency.
<P>
The minimal working debugger consists of one line
<P>
<PRE> sub DB::DB {}
</PRE>
<P>
which is quite handy as contents of [perlman:perlrun] environment variable:
<P>
<PRE> env "PERL5DB=sub DB::DB {}" perl -d your-script
</PRE>
<P>
Another (a little bit more useful) minimal debugger can be created with the
only line being
<P>
<PRE> sub DB::DB {print ++$i; scalar <STDIN>}
</PRE>
<P>
This debugger would print the sequential number of encountered statement,
and would wait for your <CODE>CR</CODE> to continue.
<P>
The following debugger is quite functional:
<P>
<PRE> {
package DB;
sub DB {}
sub sub {print ++$i, " $sub\n"; &$sub}
}
</PRE>
<P>
It prints the sequential number of subroutine call and the name of the
called subroutine. Note that <CODE>&DB::sub</CODE> should be compiled into the package <CODE>DB</CODE>.
<P>
<HR>
<H2><A NAME="Debugger_Internals">Debugger Internals</A></H2>
<P>
At the start, the debugger reads your rc file (<EM>./.perldb</EM> or
<EM>~/.perldb</EM> under Unix), which can set important options. This file may define a
subroutine <CODE>&afterinit</CODE> to be executed after the debugger is initialized.
<P>
After the rc file is read, the debugger reads environment variable
<FONT SIZE=-1>PERLDB_OPTS</FONT> and parses it as a rest of <CODE>O ...</CODE> line in debugger prompt.
<P>
It also maintains magical internal variables, such as <CODE>@DB::dbline</CODE>,
<CODE>%DB::dbline</CODE>, which are aliases for <CODE>@{"::_<current_file"}</CODE>
<CODE>%{"::_<current_file"}</CODE>. Here <CODE>current_file</CODE> is the currently selected (with the debugger's <CODE>f</CODE> command, or by flow of execution) file.
<P>
Some functions are provided to simplify customization. See <A HREF="#Debugger_Customization">Debugger Customization</A> for description of <CODE>DB::parse_options(string)</CODE>. The function <CODE>DB::dump_trace(skip[, count])</CODE> skips the specified number of frames, and returns a list containing info
about the caller frames (all if <CODE>count</CODE> is missing). Each entry is a hash with keys
<CODE>context</CODE> (<CODE>$</CODE> or <CODE>@</CODE>), [perlfunc:sub|sub] (subroutine name, or info about eval), <CODE>args</CODE> ([perlfunc:undef|undef] or a reference to an array), <CODE>file</CODE>, and
<CODE>line</CODE>.
<P>
The function <CODE>DB::print_trace(FH, skip[, count[, short]])</CODE> prints formatted info about caller frames. The last two functions may be
convenient as arguments to <CODE><</CODE>, <CODE><<</CODE> commands.
<P>
<HR>
<H2><A NAME="Other_resources">Other resources</A></H2>
<P>
You did try the <STRONG>-w</STRONG> switch, didn't you?
<P>
<HR>
<H2><A NAME="BUGS">BUGS</A></H2>
<P>
You cannot get the stack frame information or otherwise debug functions that were not compiled by Perl, such as
<FONT SIZE=-1>C</FONT> or
<FONT SIZE=-1>C++</FONT> extensions.
<P>
If you alter your <CODE>@_</CODE> arguments in a subroutine (such as with <STRONG>shift</STRONG>
or <STRONG>pop</STRONG>, the stack backtrace will not show the original values.
<P>
<HR>
<H1><A NAME="Debugging_Perl_memory_usage">Debugging Perl memory usage</A></H1>
<P>
Perl is <EM>very</EM> frivolous with memory. There is a saying that to estimate memory usage of
Perl, assume a reasonable algorithm of allocation, and multiply your
estimages by 10. This is not absolutely true, but may give you a good grasp
of what happens.
<P>
Say, an integer cannot take less than 20 bytes of memory, a float cannot take less than 24 bytes, a string cannot take less than 32 bytes (all these examples assume 32-bit architectures, the result are much worse on 64-bit architectures). If a variable is accessed in two of three different ways (which require an integer, a float, or a string), the memory footprint may increase by another 20 bytes.
<FONT SIZE=-1>A</FONT> sloppy
<CODE>malloc()</CODE> implementation will make these numbers yet more.
<P>
On the opposite end of the scale, a declaration like
<P>
<PRE> sub foo;
</PRE>
<P>
may take (on some versions of perl) up to 500 bytes of memory.
<P>
Off-the-cuff anecdotal estimates of a code bloat give a factor around 8.
This means that the compiled form of reasonable (commented indented etc.)
code will take approximately 8 times more than the disk space the code
takes.
<P>
There are two Perl-specific ways to analyze the memory usage:
<FONT SIZE=-1>$ENV{PERL_DEBUG_MSTATS}</FONT> and <STRONG>-DL</STRONG> switch. First one is available only if perl is compiled with Perl's
<CODE>malloc(),</CODE> the second one only
if Perl compiled with <CODE>-DDEBUGGING</CODE> (as with giving <CODE>-D optimise=-g</CODE>
option to <EM>Configure</EM>).
<P>
<HR>
<H2><A NAME="Using_C_ENV_PERL_DEBUG_MSTATS_">Using <CODE>$ENV{PERL_DEBUG_MSTATS}</CODE></A></H2>
<P>
If your perl is using Perl's
<CODE>malloc(),</CODE> and compiled with
correct switches (this is the default), then it will print memory usage
statistics after compiling your code (if <CODE>$ENV{PERL_DEBUG_MSTATS}</CODE> > 1), and before termination of the script (if
<CODE>$ENV{PERL_DEBUG_MSTATS}</CODE> >= 1). The report format is similar to one in the following example:
<P>
<PRE> env PERL_DEBUG_MSTATS=2 perl -e "require Carp"
Memory allocation statistics after compilation: (buckets 4(4)..8188(8192)
14216 free: 130 117 28 7 9 0 2 2 1 0 0
437 61 36 0 5
60924 used: 125 137 161 55 7 8 6 16 2 0 1
74 109 304 84 20
Total sbrk(): 77824/21:119. Odd ends: pad+heads+chain+tail: 0+636+0+2048.
Memory allocation statistics after execution: (buckets 4(4)..8188(8192)
30888 free: 245 78 85 13 6 2 1 3 2 0 1
315 162 39 42 11
175816 used: 265 176 1112 111 26 22 11 27 2 1 1
196 178 1066 798 39
Total sbrk(): 215040/47:145. Odd ends: pad+heads+chain+tail: 0+2192+0+6144.
</PRE>
<P>
It is possible to ask for such a statistic at arbitrary moment by usind Devel::Peek::mstats() (module Devel::Peek is available on
<FONT SIZE=-1>CPAN).</FONT>
<P>
Here is the explanation of different parts of the format:
<DL>
<DT><STRONG><A NAME="item_buckets">buckets SMALLEST(APPROX)..GREATEST(APPROX)</A></STRONG><P>
<DD>
Perl's
<CODE>malloc()</CODE> uses bucketed
allocations. Every request is rounded up to the closest bucket size
available, and a bucket of these size is taken from the pool of the buckets
of this size.
<P>
The above line describes limits of buckets currently in use. Each bucket
has two sizes: memory footprint, and the maximal size of user data which
may be put into this bucket. Say, in the above example the smallest bucket
is both sizes 4. The biggest bucket has usable size 8188, and the memory
footprint 8192.
<P>
With debugging Perl some buckets may have negative usable size. This means
that these buckets cannot (and will not) be used. For greater buckets the
memory footprint may be one page greater than a power of 2. In such a case
the corresponding power of two is printed instead in the <CODE>APPROX</CODE> field above.
<P><DT><STRONG><A NAME="item_Free">Free/Used</A></STRONG><P>
<DD>
The following 1 or 2 rows of numbers correspond to the number of buckets of
each size between <CODE>SMALLEST</CODE> and <CODE>GREATEST</CODE>. In the first row the sizes (memory footprints) of buckets are powers of
two (or possibly one page greater). In the second row (if present) the
memory footprints of the buckets are between memory footprints of two
buckets ``above''.
<P>
Say, with the above example the memory footprints are (with current
algorith)
<P>
<PRE> free: 8 16 32 64 128 256 512 1024 2048 4096 8192
4 12 24 48 80
</PRE>
<P>
With non-<CODE>DEBUGGING</CODE> perl the buckets starting from <CODE>128</CODE>-long ones have 4-byte overhead, thus 8192-long bucket may take up to
8188-byte-long allocations.
<P><DT><STRONG><A NAME="item_Total">Total sbrk(): SBRKed/SBRKs:CONTINUOUS</A></STRONG><P>
<DD>
The first two fields give the total amount of memory perl
<CODE>sbrk()ed,</CODE> and number of
<CODE>sbrk()s</CODE> used. The third number is what perl thinks about continuity of returned chunks. As far as this number is positive,
<CODE>malloc()</CODE> will assume that it is probable that
<CODE>sbrk()</CODE> will provide continuous memory.
<P>
The amounts
<CODE>sbrk()ed</CODE> by external
libraries is not counted.
<P><DT><STRONG><A NAME="item_pad">pad: 0</A></STRONG><P>
<DD>
The amount of
<CODE>sbrk()ed</CODE> memory needed to
keep buckets aligned.
<P><DT><STRONG><A NAME="item_heads">heads: 2192</A></STRONG><P>
<DD>
While memory overhead of bigger buckets is kept inside the bucket, for
smaller buckets it is kept in separate areas. This field gives the total
size of these areas.
<P><DT><STRONG><A NAME="item_chain">chain: 0</A></STRONG><P>
<DD>
<CODE>malloc()</CODE> may want to
subdivide a bigger bucket into smaller buckets. If only a part of the
deceased-bucket is left non-subdivided, the rest is kept as an element of a
linked list. This field gives the total size of these chunks.
<P><DT><STRONG><A NAME="item_tail">tail: 6144</A></STRONG><P>
<DD>
To minimize amount of
<CODE>sbrk()s</CODE>
<CODE>malloc()</CODE> asks for more memory. This field gives the size of the yet-unused part, which is
<CODE>sbrk()ed,</CODE> but never touched.
</DL>
<P>
<HR>
<H2><A NAME="Example_of_using_B_DL_switch">Example of using <STRONG>-DL</STRONG> switch</A></H2>
<P>
Below we show how to analyse memory usage by
<P>
<PRE> do 'lib/auto/POSIX/autosplit.ix';
</PRE>
<P>
The file in question contains a header and 146 lines similar to
<P>
<PRE> sub getcwd ;
</PRE>
<P>
<STRONG>Note:</STRONG> <EM>the discussion below supposes 32-bit architecture. In the
newer versions of perl the memory usage of the constructs discussed
here is much improved, but the story discussed below is a real-life
story. This story is very terse, and assumes more than cursory
knowledge of Perl internals.</EM>
<P>
Here is the itemized list of Perl allocations performed during parsing of
this file:
<P>
<PRE> !!! "after" at test.pl line 3.
Id subtot 4 8 12 16 20 24 28 32 36 40 48 56 64 72 80 80+
0 02 13752 . . . . 294 . . . . . . . . . . 4
0 54 5545 . . 8 124 16 . . . 1 1 . . . . . 3
5 05 32 . . . . . . . 1 . . . . . . . .
6 02 7152 . . . . . . . . . . 149 . . . . .
7 02 3600 . . . . . 150 . . . . . . . . . .
7 03 64 . -1 . 1 . . 2 . . . . . . . . .
7 04 7056 . . . . . . . . . . . . . . . 7
7 17 38404 . . . . . . . 1 . . 442 149 . . 147 .
9 03 2078 17 249 32 . . . . 2 . . . . . . . .
</PRE>
<P>
To see this list insert two [perlman:perlguts] statements around the call:
<P>
<PRE> warn('!');
do 'lib/auto/POSIX/autosplit.ix';
warn('!!! "after"');
</PRE>
<P>
and run it with <STRONG>-DL</STRONG> option. The first
<CODE>warn()</CODE> will print memory allocation info before the parsing of the file, and will memorize the statistics at this point (we ignore what it prints). The second
<CODE>warn()</CODE> will print increments w.r.t. this memorized statistics. This is the above printout.
<P>
Different <EM>Id</EM>s on the left correspond to different subsystems of perl interpreter, they are just first argument given to perl memory allocation
<FONT SIZE=-1>API</FONT>
<CODE>New().</CODE> To find what
<CODE>9 03</CODE> means [perlfunc:grep|grep] the perl source for <CODE>903</CODE>. You will see that it is <EM>util.c</EM>, function
<CODE>savepvn().</CODE> This function is used to store a copy of existing chunk of memory. Using
<FONT SIZE=-1>C</FONT> debugger, one can see that it is called either directly from
<CODE>gv_init(),</CODE> or via
<CODE>sv_magic(),</CODE> and
<CODE>gv_init()</CODE> is called from
<CODE>gv_fetchpv()</CODE> - which is called from
<CODE>newSUB().</CODE>
<P>
<STRONG>Note:</STRONG> to reach this place in debugger and skip all the calls to savepvn during the compilation of the main script, set a
<FONT SIZE=-1>C</FONT> breakpoint in
<CODE>Perl_warn(),</CODE>
[perlfunc:continue|continue] this point is reached, <EM>then</EM> set breakpoint in
<CODE>Perl_savepvn().</CODE> Note that you may need to skip a handful of
<CODE>Perl_savepvn()</CODE> which do not correspond to mass production of CVs (there are more
<CODE>903</CODE> allocations than 146 similar lines of
<EM>lib/auto/POSIX/autosplit.ix</EM>). Note also that <CODE>Perl_</CODE> prefixes are added by macroization code in perl header files to avoid
conflicts with external libraries.
<P>
Anyway, we see that <CODE>903</CODE> ids correspond to creation of globs, twice per glob - for glob name, and
glob stringification magic.
<P>
Here are explanations for other <EM>Id</EM>s above:
<OL>
<LI><STRONG><A NAME="item_7">7</A></STRONG>
<P>
is for creation of bigger <CODE>XPV*</CODE> structures. In the above case it creates 3 [perlman:perlguts] per subroutine, one for a list of lexical variable names, one for a
scratchpad (which contains lexical variables and
<CODE>targets</CODE>), and one for the array of scratchpads needed for recursion.
<P>
It also creates a <CODE>GV</CODE> and a <CODE>CV</CODE> per subroutine (all called from
<CODE>start_subparse()).</CODE>
<P><LI><STRONG><A NAME="item_2">2</A></STRONG>
Creates
<FONT SIZE=-1>C</FONT> array corresponding to the [perlman:perlguts] of scratchpads, and the scratchpad itself (the first fake entry of this
scratchpad is created though the subroutine itself is not defined yet).
<P>
It also creates
<FONT SIZE=-1>C</FONT> arrays to keep data for the stash (this is one
<FONT SIZE=-1>HV,</FONT> but it grows, thus there are 4 big allocations: the big chunks are not freeed, but are kept as additional arenas for
[perlman:perlguts] allocations).
<P><LI><STRONG>4</STRONG>
creates a <CODE>HEK</CODE> for the name of the glob for the subroutine (this name is a key in a <EM>stash</EM>).
<P>
Big allocations with this <EM>Id</EM> correspond to allocations of new arenas to keep <CODE>HE</CODE>.
<P><LI><STRONG>2</STRONG>
creates a <CODE>GP</CODE> for the glob for the subroutine.
<P><LI><STRONG>2</STRONG>
creates the <CODE>MAGIC</CODE> for the glob for the subroutine.
<P><LI><STRONG>4</STRONG>
creates <EM>arenas</EM> which keep SVs.
</OL>
<P>
<HR>
<H2><A NAME="B_DL_details"><STRONG>-DL</STRONG> details</A></H2>
<P>
If Perl is run with <STRONG>-DL</STRONG> option, then
<CODE>warn()s</CODE> which start with `!'
behave specially. They print a list of <EM>categories</EM> of memory allocations, and statistics of allocations of different sizes for
these categories.
<P>
If
<CODE>warn()</CODE> string starts with
<DL>
<DT><STRONG><A NAME="item__">!!!</A></STRONG><P>
<DD>
print changed categories only, print the differences in counts of
allocations;
<P><DT><STRONG>!!</STRONG><P>
<DD>
print grown categories only; print the absolute values of counts, and
totals;
<P><DT><STRONG>!</STRONG><P>
<DD>
print nonempty categories, print the absolute values of counts and totals.
</DL>
<P>
<HR>
<H2><A NAME="Limitations_of_B_DL_statistic">Limitations of <STRONG>-DL</STRONG> statistic</A></H2>
<P>
If an extension or an external library does not use Perl
<FONT SIZE=-1>API</FONT> to allocate memory, these allocations are not
counted.
<P>
<HR>
<H1><A NAME="Debugging_regular_expressions">Debugging regular expressions</A></H1>
<P>
There are two ways to enable debugging output for regular expressions.
<P>
If your perl is compiled with <CODE>-DDEBUGGING</CODE>, you may use the
<STRONG>-Dr</STRONG> flag on the command line.
<P>
Otherwise, one can <CODE>use re 'debug'</CODE>, which has effects both at compile time, and at run time (and is <EM>not</EM> lexically scoped).
<P>
<BR>[perlman:perldebug2|More...]<BR>
<BR>Return to the [Library]<BR>