Language ReferenceDebug debuggerDaftar Isi NAME perldebug - Perl debugging DESCRIPTIONFirst of all, have you tried using the -w switch? If you're new to the Perl debugger, you may prefer to readperldebtut, which is a tutorial introduction to the debugger. The Perl DebuggerIf you invoke Perl with the -d switch, your script runs under thePerl source debugger. This works like an interactive Perlenvironment, prompting for debugger commands that let you examinesource code, set breakpoints, get stack backtraces, change the values ofvariables, etc. This is so convenient that you often fire upthe debugger all by itself just to test out Perl constructsinteractively to see what they do. For example: - $ perl -d -e 42
In Perl, the debugger is not a separate program the way it usually is in thetypical compiled environment. Instead, the -d flag tells the compilerto insert source information into the parse trees it's about to hand offto the interpreter. That means your code must first compile correctlyfor the debugger to work on it. Then when the interpreter starts up, itpreloads a special Perl library file containing the debugger. The program will halt right before the first run-time executablestatement (but see below regarding compile-time statements) and ask youto enter a debugger command. Contrary to popular expectations, wheneverthe debugger halts and shows you a line of code, it always displays theline it's about to execute, rather than the one it has just executed. Any command not recognized by the debugger is directly executed(eval 'd) as Perl code in the current package. (The debuggeruses the DB package for keeping its own state information.) Note that the said eval is bound by an implicit scope. As aresult any newly introduced lexical variable or any modifiedcapture buffer content is lost after the eval. The debugger is anice environment to learn Perl, but if you interactively experiment usingmaterial which should be in the same scope, stuff it in one line. For any text entered at the debugger prompt, leading and trailing whitespaceis first stripped before further processing. If a debugger commandcoincides with some function in your own program, merely precede thefunction with something that doesn't look like a debugger command, suchas a leading ; or perhaps a + , or by wrapping it with parenthesesor braces. Calling the DebuggerThere are several ways to call the debugger: - perl -d program_name
On the given program identified by program_name . - perl -d -e 0
Interactively supply an arbitrary expression using -e . - perl -d:Ptkdb program_name
Debug a given program via the Devel::Ptkdb GUI. - perl -dt threaded_program_name
Debug a given program using threads (experimental).
Debugger CommandsThe interactive debugger understands the following commands: - h
Prints out a summary help message - h [command]
Prints out a help message for the given debugger command. - h h
The special argument of h h produces the entire help page, which is quite long. If the output of the h h command (or any command, for that matter) scrollspast your screen, precede the command with a leading pipe symbol sothat it's run through your pager, as in - DB> |h h
You may change the pager which is used via o pager=... command. - p expr
Same as print {$DB::OUT} expr in the current package. In particular,because this is just Perl's own print function, this means that nesteddata structures and objects are not dumped, unlike with the x command. The DB::OUT filehandle is opened to /dev/tty, regardless ofwhere STDOUT may be redirected to. - x [maxdepth] expr
Evaluates its expression in list context and dumps out the result in apretty-printed fashion. Nested data structures are printed outrecursively, unlike the real print function in Perl. When dumpinghashes, you'll probably prefer 'x \%h' rather than 'x %h'.See Dumpvalue if you'd like to do this yourself. The output format is governed by multiple options described underConfigurable Options. If the maxdepth is included, it must be a numeral N; the value isdumped only N levels deep, as if the dumpDepth option had beentemporarily set to N. - V [pkg [vars]]
Display all (or some) variables in package (defaulting to main )using a data pretty-printer (hashes show their keys and values soyou see what's what, control characters are made printable, etc.).Make sure you don't put the type specifier (like $ ) there, justthe symbol names, like this: - V DB filename line
Use ~pattern and !pattern for positive and negative regexes. This is similar to calling the x command on each applicable var. - X [vars]
Same as V currentpackage [vars] . - y [level [vars]]
Display all (or some) lexical variables (mnemonic: mY variables)in the current scope or level scopes higher. You can limit thevariables that you see with vars which works exactly as it doesfor the V and X commands. Requires the PadWalker moduleversion 0.08 or higher; will warn if this isn't installed. Outputis pretty-printed in the same style as for V and the format iscontrolled by the same options. - T
Produce a stack backtrace. See below for details on its output. - s [expr]
Single step. Executes until the beginning of anotherstatement, descending into subroutine calls. If an expression issupplied that includes function calls, it too will be single-stepped. - n [expr]
Next. Executes over subroutine calls, until the beginningof the next statement. If an expression is supplied that includesfunction calls, those functions will be executed with stops beforeeach statement. - r
Continue until the return from the current subroutine.Dump the return value if the PrintRet option is set (default). - <CR>
Repeat last n or s command. - c [line|sub]
Continue, optionally inserting a one-time-only breakpointat the specified line or subroutine. - l
List next window of lines. - l min+incr
List incr+1 lines starting at min . - l min-max
List lines min through max . l - is synonymous to - . - l line
List a single line. - l subname
List first window of lines from subroutine. subname maybe a variable that contains a code reference. - -
List previous window of lines. - v [line]
View a few lines of code around the current line. - .
Return the internal debugger pointer to the line lastexecuted, and print out that line. - f filename
Switch to viewing a different file or eval statement. If filenameis not a full pathname found in the values of %INC, it is considereda regex. eval ed strings (when accessible) are considered to be filenames:f (eval 7) and f eval 7\b access the body of the 7th eval ed string(in the order of execution). The bodies of the currently executed eval and of eval ed strings that define subroutines are saved and thusaccessible.
- /pattern/
Search forwards for pattern (a Perl regex); final / is optional.The search is case-insensitive by default. - ?pattern?
Search backwards for pattern; final ? is optional.The search is case-insensitive by default. - L [abw]
List (default all) actions, breakpoints and watch expressions - S [[!]regex]
List subroutine names [not] matching the regex. - t [n]
Toggle trace mode (see also the AutoTrace option).Optional argument is the maximum number of levels to trace belowthe current one; anything deeper than that will be silent. - t [n] expr
Trace through execution of expr .Optional first argument is the maximum number of levels to trace belowthe current one; anything deeper than that will be silent.See Frame Listing Output Examples in perldebguts for examples. - b
Sets breakpoint on current line - b [line] [condition]
Set a breakpoint before the given line. If a conditionis specified, it's evaluated each time the statement is reached: abreakpoint is taken only if the condition is true. Breakpoints mayonly be set on lines that begin an executable statement. Conditionsdon't use if : - b 237 $x > 30
- b 237 ++$count237 < 11
- b 33 /pattern/i
If the line number is . , sets a breakpoint on the current line: - b . $n > 100
- b [file]:[line] [condition]
Set a breakpoint before the given line in a (possibly different) file. If acondition is specified, it's evaluated each time the statement is reached: abreakpoint is taken only if the condition is true. Breakpoints may only be seton lines that begin an executable statement. Conditions don't use if : - b lib/MyModule.pm:237 $x > 30
- b /usr/lib/perl5/site_perl/CGI.pm:100 ++$count100 < 11
- b subname [condition]
Set a breakpoint before the first line of the named subroutine. subname maybe a variable containing a code reference (in this case conditionis not supported). - b postpone subname [condition]
Set a breakpoint at first line of subroutine after it is compiled. - b load filename
Set a breakpoint before the first executed line of the filename,which should be a full pathname found amongst the %INC values. - b compile subname
Sets a breakpoint before the first statement executed after the specifiedsubroutine is compiled. - B line
Delete a breakpoint from the specified line. - B *
Delete all installed breakpoints. - disable [file]:[line]
Disable the breakpoint so it won't stop the execution of the program. Breakpoints are enabled by default and can be re-enabled using the enable command. - disable [line]
Disable the breakpoint so it won't stop the execution of the program. Breakpoints are enabled by default and can be re-enabled using the enable command. This is done for a breakpoint in the current file. - enable [file]:[line]
Enable the breakpoint so it will stop the execution of the program. - enable [line]
Enable the breakpoint so it will stop the execution of the program. This is done for a breakpoint in the current file. - a [line] command
Set an action to be done before the line is executed. If line isomitted, set an action on the line about to be executed.The sequence of steps taken by the debugger is - 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
For example, this will print out $foo every time line53 is passed: - a 53 print "DB FOUND $foo\n"
- A line
Delete an action from the specified line. - A *
Delete all installed actions. - w expr
Add a global watch-expression. Whenever a watched global changes thedebugger will stop and display the old and new values. - W expr
Delete watch-expression - W *
Delete all watch-expressions. - o
Display all options. - o booloption ...
Set each listed Boolean option to the value 1 . - o anyoption? ...
Print out the value of one or more options. - o option=value ...
Set the value of one or more options. If the value has internalwhitespace, it should be quoted. For example, you could set opager="less -MQeicsNfr" to call less with those specific options.You may use either single or double quotes, but if you do, you mustescape any embedded instances of same sort of quote you began with,as well as any escaping any escapes that immediately precede thatquote but which are not meant to escape the quote itself. In otherwords, you follow single-quoting rules irrespective of the quote;eg: o option='this isn\'t bad' or o option="She said, \"Isn'tit?\"" . For historical reasons, the =value is optional, but defaults to1 only where it is safe to do so--that is, mostly for Booleanoptions. It is always better to assign a specific value using = .The option can be abbreviated, but for clarity probably shouldnot be. Several options can be set together. See Configurable Optionsfor a list of these. - < ?
List out all pre-prompt Perl command actions. - < [ command ]
Set an action (Perl command) to happen before every debugger prompt.A multi-line command may be entered by backslashing the newlines. - < *
Delete all pre-prompt Perl command actions. - << command
Add an action (Perl command) to happen before every debugger prompt.A multi-line command may be entered by backwhacking the newlines. - > ?
List out post-prompt Perl command actions. - > command
Set an action (Perl command) to happen after the prompt when you'vejust given a command to return to executing the script. A multi-linecommand may be entered by backslashing the newlines (we bet youcouldn't have guessed this by now). - > *
Delete all post-prompt Perl command actions. - >> command
Adds an action (Perl command) to happen after the prompt when you'vejust given a command to return to executing the script. A multi-linecommand may be entered by backslashing the newlines. - { ?
List out pre-prompt debugger commands. - { [ command ]
Set an action (debugger command) to happen before every debugger prompt.A multi-line command may be entered in the customary fashion. Because this command is in some senses new, a warning is issued ifyou appear to have accidentally entered a block instead. If that'swhat you mean to do, write it as with ;{ ... } or evendo { ... } . - { *
Delete all pre-prompt debugger commands. - {{ command
Add an action (debugger command) to happen before every debugger prompt.A multi-line command may be entered, if you can guess how: see above. - ! number
Redo a previous command (defaults to the previous command). - ! -number
Redo number'th previous command. - ! pattern
Redo last command that started with pattern.See o recallCommand , too. - !! cmd
Run cmd in a subprocess (reads from DB::IN, writes to DB::OUT) Seeo shellBang , also. Note that the user's current shell (well,their $ENV{SHELL} variable) will be used, which can interferewith proper interpretation of exit status or signal and coredumpinformation. - source file
Read and execute debugger commands from file.file may itself contain source commands. - H -number
Display last n commands. Only commands longer than one character arelisted. If number is omitted, list them all. - q or ^D
Quit. ("quit" doesn't work for this, unless you've made an alias)This is the only supported way to exit the debugger, though typingexit twice might work. Set the inhibit_exit option to 0 if you want to be able to stepoff the end the script. You may also need to set $finished to 0if you want to step through global destruction. - R
Restart the debugger by exec() ing a new session. We try to maintainyour history across this, but internal settings and command-line optionsmay be lost. The following setting are currently preserved: history, breakpoints,actions, debugger options, and the Perl command-lineoptions -w, -I, and -e. - |dbcmd
Run the debugger command, piping DB::OUT into your current pager. - ||dbcmd
Same as |dbcmd but DB::OUT is temporarily select ed as well. - = [alias value]
Define a command alias, like - = quit q
or list current aliases. - command
Execute command as a Perl statement. A trailing semicolon will besupplied. If the Perl statement would otherwise be confused for aPerl debugger, use a leading semicolon, too. - m expr
List which methods may be called on the result of the evaluatedexpression. The expression may evaluated to a reference to ablessed object, or to a package name. - M
Display all loaded modules and their versions. - man [manpage]
Despite its name, this calls your system's default documentationviewer on the given page, or on the viewer itself if manpage isomitted. If that viewer is man, the current Config informationis used to invoke man using the proper MANPATH or -Mmanpath option. Failed lookups of the form XXX that matchknown manpages of the form perlXXX will be retried. This letsyou type man debug or man op from the debugger. On systems traditionally bereft of a usable man command, thedebugger invokes perldoc. Occasionally this determination isincorrect due to recalcitrant vendors or rather more felicitously,to enterprising users. If you fall into either category, justmanually set the $DB::doccmd variable to whatever viewer to viewthe Perl documentation on your system. This may be set in an rcfile, or through direct assignment. We're still waiting for aworking example of something along the lines of: - $DB::doccmd = 'netscape -remote http://something.here/';
Configurable OptionsThe debugger has numerous options settable using the o command,either interactively or from the environment or an rc file.(./.perldb or ~/.perldb under Unix.) recallCommand , ShellBang The characters used to recall command or spawn shell. Bydefault, both are set to ! , which is unfortunate. pager Program to use for output of pager-piped commands (those beginningwith a | character.) By default, $ENV{PAGER} will be used.Because the debugger uses your current terminal characteristicsfor bold and underlining, if the chosen pager does not pass escapesequences through unchanged, the output of some debugger commandswill not be readable when sent through the pager. tkRunning Run Tk while prompting (with ReadLine). signalLevel , warnLevel , dieLevel Level of verbosity. By default, the debugger leaves your exceptionsand warnings alone, because altering them can break correctly runningprograms. It will attempt to print a message when uncaught INT, BUS, orSEGV signals arrive. (But see the mention of signals in BUGS below.) To disable this default safe mode, set these values to something higherthan 0. At a level of 1, you get backtraces upon receiving any kindof warning (this is often annoying) or exception (this isoften valuable). Unfortunately, the debugger cannot discern fatalexceptions from non-fatal ones. If dieLevel is even 1, then yournon-fatal exceptions are also traced and unceremoniously altered if theycame from eval'ed strings or from any kind of eval within modulesyou're attempting to load. If dieLevel is 2, the debugger doesn'tcare where they came from: It usurps your exception handler and printsout a trace, then modifies all exceptions with its own embellishments.This may perhaps be useful for some tracing purposes, but tends to hopelesslydestroy any program that takes its exception handling seriously. AutoTrace Trace mode (similar to t command, but can be put intoPERLDB_OPTS ). LineInfo File or pipe to print line number info to. If it is a pipe (say,|visual_perl_db ), then a short message is used. This is themechanism used to interact with a slave editor or visual debugger,such as the special vi or emacs hooks, or the ddd graphicaldebugger. inhibit_exit If 0, allows stepping off the end of the script. PrintRet Print return value after r command if set (default). ornaments Affects screen appearance of the command line (see Term::ReadLine).There is currently no way to disable these, which can rendersome output illegible on some displays, or with some pagers.This is considered a bug. frame Affects the printing of messages upon entry and exit from subroutines. Ifframe & 2 is false, messages are printed on entry only. (Printingon exit might be useful if interspersed with other messages.) If frame & 4 , arguments to functions are printed, plus contextand caller info. If frame & 8 , overloaded stringify andtie d FETCH is enabled on the printed arguments. If frame& 16 , the return value from the subroutine is printed. The length at which the argument list is truncated is governed by thenext option: maxTraceLen Length to truncate the argument list when the frame option'sbit 4 is set. windowSize Change the size of code list window (default is 10 lines).
The following options affect what happens with V , X , and x commands: arrayDepth , hashDepth Print only first N elements ('' for all). dumpDepth Limit recursion depth to N levels when dumping structures.Negative values are interpreted as infinity. Default: infinity. compactDump , veryCompact Change the style of array and hash output. If compactDump , short arraymay be printed on one line. globPrint Whether to print contents of globs. DumpDBFiles Dump arrays holding debugged files. DumpPackages Dump symbol tables of packages. DumpReused Dump contents of "reused" addresses. quote , HighBit , undefPrint Change the style of string dump. The default value for quote is auto ; one can enable double-quotish or single-quotish formatby setting it to " or ' , respectively. By default, characterswith their high bit set are printed verbatim. UsageOnly Rudimentary per-package memory usage dump. Calculates totalsize of strings found in variables in the package. This does notinclude lexicals in a module's file scope, or lost in closures.
After the rc file is read, the debugger reads the $ENV{PERLDB_OPTS} environment variable and parses this as the remainder of a "O ..."line as one might enter at the debugger prompt. You may place theinitialization options TTY , noTTY , ReadLine , and NonStop there. If your rc file contains: - parse_options("NonStop=1 LineInfo=db.out AutoTrace");
then your script will run without human intervention, putting traceinformation into the file db.out. (If you interrupt it, you'dbetter reset LineInfo to /dev/tty if you expect to see anything.) TTY The TTY to use for debugging I/O. noTTY If set, the debugger goes into NonStop mode and will not connect to a TTY. Ifinterrupted (or if control goes to the debugger via explicit setting of$DB::signal or $DB::single from the Perl script), it connects to a TTYspecified in the TTY option at startup, or to a tty found atruntime using the Term::Rendezvous module of your choice. This module should implement a method named new that returns an objectwith two methods: IN and OUT . These should return filehandles to usefor debugging input and output correspondingly. The new method shouldinspect an argument containing the value of $ENV{PERLDB_NOTTY} atstartup, or "$ENV{HOME}/.perldbtty$$" otherwise. This file is notinspected for proper ownership, so security hazards are theoreticallypossible. ReadLine If false, readline support in the debugger is disabled in orderto debug applications that themselves use ReadLine. NonStop If set, the debugger goes into non-interactive mode until interrupted, orprogrammatically by setting $DB::signal or $DB::single.
Here's an example of using the $ENV{PERLDB_OPTS} variable: - $ PERLDB_OPTS="NonStop frame=2" perl -d myprogram
That will run the script myprogram without human intervention,printing out the call tree with entry and exit points. Note thatNonStop=1 frame=2 is equivalent to N f=2 , and that originally,options could be uniquely abbreviated by the first letter (modulothe Dump* options). It is nevertheless recommended that youalways spell them out in full for legibility and future compatibility. Other examples include - $ PERLDB_OPTS="NonStop LineInfo=listing frame=2" perl -d myprogram
which runs script non-interactively, printing info on each entryinto a subroutine and each executed line into the file named listing.(If you interrupt it, you would better reset LineInfo to something"interactive"!) Other examples include (using standard shell syntax to show environmentvariable settings): - $ ( PERLDB_OPTS="NonStop frame=1 AutoTrace LineInfo=tperl.out"
- perl -d myprogram )
which may be useful for debugging a program that uses Term::ReadLine itself. Do not forget to detach your shell from the TTY in the window thatcorresponds to /dev/ttyXX, say, by issuing a command like - $ sleep 1000000
See Debugger Internals in perldebguts for details. Debugger Input/Output- Prompt
The debugger prompt is something like - DB<8>
or even - DB<<17>>
where that number is the command number, and which you'd use toaccess with the built-in csh-like history mechanism. For example,!17 would repeat command number 17. The depth of the anglebrackets indicates the nesting depth of the debugger. You couldget more than one set of brackets, for example, if you'd alreadyat a breakpoint and then printed the result of a function call thatitself has a breakpoint, or you step into an expression via s/n/texpression command. - Multiline commands
If you want to enter a multi-line command, such as a subroutinedefinition with several statements or a format, escape the newlinethat would normally end the debugger command with a backslash.Here's an example: - DB<1> for (1..4) { \
- cont: print "ok\n"; \
- cont: }
- ok
- ok
- ok
- ok
Note that this business of escaping a newline is specific to interactivecommands typed into the debugger. - Stack backtrace
Here's an example of what a stack backtrace via T command mightlook like: - $ = main::infested called from file 'Ambulation.pm' line 10
- @ = Ambulation::legs(1, 2, 3, 4) called from file 'camel_flea' line 7
- $ = main::pests('bactrian', 4) called from file 'camel_flea' line 4
The left-hand character up there indicates the context in which thefunction was called, with $ and @ meaning scalar or listcontexts respectively, and . meaning void context (which isactually a sort of scalar context). The display above saysthat you were in the function main::infested when you ran thestack dump, and that it was called in scalar context from line10 of the file Ambulation.pm, but without any arguments at all,meaning it was called as &infested . The next stack frame showsthat the function Ambulation::legs was called in list contextfrom the camel_flea file with four arguments. The last stackframe shows that main::pests was called in scalar context,also from camel_flea, but from line 4. If you execute the T command from inside an active use statement, the backtrace will contain both a require frame andan eval frame. - Line Listing Format
This shows the sorts of output the l command can produce: - DB<<13>> l
- 101: @i{@i} = ();
- 102:b @isa{@i,$pack} = ()
- 103 if(exists $i{$prevpack} || exists $isa{$pack});
- 104 }
- 105
- 106 next
- 107==> if(exists $isa{$pack});
- 108
- 109:a if ($extra-- > 0) {
- 110: %isa = ($pack,1);
Breakable lines are marked with : . Lines with breakpoints aremarked by b and those with actions by a . The line that'sabout to be executed is marked by ==> . Please be aware that code in debugger listings may not look the sameas your original source code. Line directives and external sourcefilters can alter the code before Perl sees it, causing code to movefrom its original positions or take on entirely different forms. - Frame listing
When the frame option is set, the debugger would print entered (andoptionally exited) subroutines in different styles. See perldebgutsfor incredibly long examples of these.
Debugging Compile-Time StatementsIf you have compile-time executable statements (such as code withinBEGIN, UNITCHECK and CHECK blocks or use statements), these willnot be stopped by debugger, although require s and INIT blockswill, and compile-time statements can be traced with the AutoTrace option set in PERLDB_OPTS ). From your own Perl code, however, youcan transfer control back to the debugger using the followingstatement, which is harmless if the debugger is not running: - $DB::single = 1;
If you set $DB::single to 2, it's equivalent to havingjust typed the n command, whereas a value of 1 means the s command. The $DB::trace variable should be set to 1 to simulatehaving typed the t command. Another way to debug compile-time code is to start the debugger, set abreakpoint on the load of some module: - DB<7> b load f:/perllib/lib/Carp.pm
- Will stop on load of 'f:/perllib/lib/Carp.pm'.
and then restart the debugger using the R command (if possible). One can use bcompile subname for the same purpose. Debugger CustomizationThe debugger probably contains enough configuration hooks that youwon't ever have to modify it yourself. You may change the behaviourof the debugger from within the debugger using its o command, fromthe command line via the PERLDB_OPTS environment variable, andfrom customization files. You can do some customization by setting up a .perldb file, whichcontains initialization code. For instance, you could make aliaseslike these (the last one is one people expect to be there): - $DB::alias{'len'} = 's/^len(.*)/p length($1)/';
- $DB::alias{'stop'} = 's/^stop (at|in)/b/';
- $DB::alias{'ps'} = 's/^ps\b/p scalar /';
- $DB::alias{'quit'} = 's/^quit(\s*)/exit/';
You can change options from .perldb by using calls like this one; - parse_options("NonStop=1 LineInfo=db.out AutoTrace=1 frame=2");
The code is executed in the package DB . Note that .perldb isprocessed before processing PERLDB_OPTS . If .perldb defines thesubroutine afterinit , that function is called after debuggerinitialization ends. .perldb may be contained in the currentdirectory, or in the home directory. Because this file is sourcedin by Perl and may contain arbitrary commands, for security reasons,it must be owned by the superuser or the current user, and writableby no one but its owner. You can mock TTY input to debugger by adding arbitrary commands to@DB::typeahead. For example, your .perldb file might contain: - sub afterinit { push @DB::typeahead, "b 4", "b 6"; }
Which would attempt to set breakpoints on lines 4 and 6 immediatelyafter debugger initialization. Note that @DB::typeahead is not a supportedinterface and is subject to change in future releases. If you want to modify the debugger, copy perl5db.pl from thePerl library to another name and hack it to your heart's content.You'll then want to set your PERL5DB environment variable to saysomething like this: - BEGIN { require "myperl5db.pl" }
As a last resort, you could also use PERL5DB to customize the debuggerby directly setting internal variables or calling debugger functions. Note that any variables and functions that are not documented inthis document (or in perldebguts) are considered for internaluse only, and as such are subject to change without notice. Readline Support / History in the DebuggerAs shipped, the only command-line history supplied is a simplistic onethat checks for leading exclamation points. However, if you installthe Term::ReadKey and Term::ReadLine modules from CPAN (such asTerm::ReadLine::Gnu, Term::ReadLine::Perl, ...) you willhave full editing capabilities much like those GNU readline(3) provides.Look for these in the modules/by-module/Term directory on CPAN.These do not support normal vi command-line editing, however. A rudimentary command-line completion is also available, includinglexical variables in the current scope if the PadWalker moduleis installed. Without Readline support you may see the symbols "^[[A", "^[[C", "^[[B","^[[D"", "^H", ... when using the arrow keys and/or the backspace key. Editor Support for DebuggingIf you have the FSF's version of emacs installed on your system,it can interact with the Perl debugger to provide an integratedsoftware development environment reminiscent of its interactionswith C debuggers. Recent versions of Emacs come with astart file for making emacs act like asyntax-directed editor that understands (some of) Perl's syntax.See perlfaq3. A similar setup by Tom Christiansen for interacting with anyvendor-shipped vi and the X11 window system is also available.This works similarly to the integrated multiwindow support thatemacs provides, where the debugger drives the editor. At thetime of this writing, however, that tool's eventual location in thePerl distribution was uncertain. Users of vi should also look into vim and gvim, the mouseyand windy version, for coloring of Perl keywords. Note that only perl can truly parse Perl, so all such CASE toolsfall somewhat short of the mark, especially if you don't programyour Perl as a C programmer might. The Perl Profiler If you wish to supply an alternative debugger for Perl to run,invoke your script with a colon and a package argument given to the-d flag. Perl's alternative debuggers include a Perl profiler,Devel::NYTProf, which is available separately as a CPANdistribution. To profile your Perl program in the file mycode.pl,just type: - $ perl -d:NYTProf mycode.pl
When the script terminates the profiler will create a database of theprofile information that you can turn into reports using the profiler'stools. See <perlperf> for details. Debugging Regular Expressions use re 'debug' enables you to see the gory details of how the Perlregular expression engine works. In order to understand this typicallyvoluminous output, one must not only have some idea about how regularexpression matching works in general, but also know how Perl's regularexpressions are internally compiled into an automaton. These mattersare explored in some detail inDebugging Regular Expressions in perldebguts.
Debugging Memory UsagePerl contains internal support for reporting its own memory usage,but this is a fairly advanced concept that requires some understandingof how memory allocation works.See Debugging Perl Memory Usage in perldebguts for the details. SEE ALSOYou did try the -w switch, didn't you? perldebtut,perldebguts,re,DB,Devel::NYTProf,Dumpvalue,andperlrun. When debugging a script that uses #! and is thus normally found in$PATH, the -S option causes perl to search $PATH for it, so you don'thave to type the path or which $scriptname . - $ perl -Sd foo.pl
BUGSYou cannot get stack frame information or in any fashion debug functionsthat were not compiled by Perl, such as those from C or C++ extensions. If you alter your @_ arguments in a subroutine (such as with shift or pop ), the stack backtrace will not show the original values. The debugger does not currently work in conjunction with the -Wcommand-line switch, because it itself is not free of warnings. If you're in a slow syscall (like wait ing, accept ing, or read ingfrom your keyboard or a socket) and haven't set up your own $SIG{INT} handler, then you won't be able to CTRL-C your way back to the debugger,because the debugger's own $SIG{INT} handler doesn't understand thatit needs to raise an exception to longjmp(3) out of slow syscalls. |