{
    "mode": "man",
    "parameter": "perldebtut",
    "section": "1",
    "url": "https://www.chedong.com/phpMan.php/man/perldebtut/1/json",
    "generated": "2026-06-14T05:23:04Z",
    "sections": {
        "NAME": {
            "content": "perldebtut - Perl debugging tutorial\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "A (very) lightweight introduction in the use of the perl debugger, and a pointer to existing,\ndeeper sources of information on the subject of debugging perl programs.\n\nThere's an extraordinary number of people out there who don't appear to know anything about\nusing the perl debugger, though they use the language every day.  This is for them.\n",
            "subsections": [
                {
                    "name": "use strict",
                    "content": "First of all, there's a few things you can do to make your life a lot more straightforward\nwhen it comes to debugging perl programs, without using the debugger at all.  To demonstrate,\nhere's a simple script, named \"hello\", with a problem:\n\n#!/usr/bin/perl\n\n$var1 = 'Hello World'; # always wanted to do that :-)\n$var2 = \"$varl\\n\";\n\nprint $var2;\nexit;\n\nWhile this compiles and runs happily, it probably won't do what's expected, namely it doesn't\nprint \"Hello World\\n\" at all;  It will on the other hand do exactly what it was told to do,\ncomputers being a bit that way inclined.  That is, it will print out a newline character, and\nyou'll get what looks like a blank line.  It looks like there's 2 variables when (because of\nthe typo) there's really 3:\n\n$var1 = 'Hello World';\n$varl = undef;\n$var2 = \"\\n\";\n\nTo catch this kind of problem, we can force each variable to be declared before use by\npulling in the strict module, by putting 'use strict;' after the first line of the script.\n\nNow when you run it, perl complains about the 3 undeclared variables and we get four error\nmessages because one variable is referenced twice:\n\nGlobal symbol \"$var1\" requires explicit package name at ./t1 line 4.\nGlobal symbol \"$var2\" requires explicit package name at ./t1 line 5.\nGlobal symbol \"$varl\" requires explicit package name at ./t1 line 5.\nGlobal symbol \"$var2\" requires explicit package name at ./t1 line 7.\nExecution of ./hello aborted due to compilation errors.\n\nLuvverly! and to fix this we declare all variables explicitly and now our script looks like\nthis:\n\n#!/usr/bin/perl\nuse strict;\n\nmy $var1 = 'Hello World';\nmy $varl = undef;\nmy $var2 = \"$varl\\n\";\n\nprint $var2;\nexit;\n\nWe then do (always a good idea) a syntax check before we try to run it again:\n\n> perl -c hello\nhello syntax OK\n\nAnd now when we run it, we get \"\\n\" still, but at least we know why.  Just getting this\nscript to compile has exposed the '$varl' (with the letter 'l') variable, and simply changing\n$varl to $var1 solves the problem.\n"
                },
                {
                    "name": "Looking at data and -w and v",
                    "content": "Ok, but how about when you want to really see your data, what's in that dynamic variable,\njust before using it?\n\n#!/usr/bin/perl\nuse strict;\n\nmy $key = 'welcome';\nmy %data = (\n'this' => qw(that),\n'tom' => qw(and jerry),\n'welcome' => q(Hello World),\n'zip' => q(welcome),\n);\nmy @data = keys %data;\n\nprint \"$data{$key}\\n\";\nexit;\n\nLooks OK, after it's been through the syntax check (perl -c scriptname), we run it and all we\nget is a blank line again!  Hmmmm.\n\nOne common debugging approach here, would be to liberally sprinkle a few print statements, to\nadd a check just before we print out our data, and another just after:\n\nprint \"All OK\\n\" if grep($key, keys %data);\nprint \"$data{$key}\\n\";\nprint \"done: '$data{$key}'\\n\";\n\nAnd try again:\n\n> perl data\nAll OK\n\ndone: ''\n\nAfter much staring at the same piece of code and not seeing the wood for the trees for some\ntime, we get a cup of coffee and try another approach.  That is, we bring in the cavalry by\ngiving perl the '-d' switch on the command line:\n\n> perl -d data\nDefault die handler restored.\n\nLoading DB routines from perl5db.pl version 1.07\nEditor support available.\n\nEnter h or `h h' for help, or `man perldebug' for more help.\n\nmain::(./data:4):     my $key = 'welcome';\n\nNow, what we've done here is to launch the built-in perl debugger on our script.  It's\nstopped at the first line of executable code and is waiting for input.\n\nBefore we go any further, you'll want to know how to quit the debugger: use just the letter\n'q', not the words 'quit' or 'exit':\n\nDB<1> q\n>\n\nThat's it, you're back on home turf again.\n\nhelp\nFire the debugger up again on your script and we'll look at the help menu.  There's a couple\nof ways of calling help: a simple 'h' will get the summary help list, '|h' (pipe-h) will pipe\nthe help through your pager (which is (probably 'more' or 'less'), and finally, 'h h'\n(h-space-h) will give you the entire help screen.  Here is the summary page:\n\nD1h\n\nList/search source lines:               Control script execution:\nl [ln|sub]  List source code            T           Stack trace\n- or .      List previous/current line  s [expr]    Single step\n[in expr]\nv [line]    View around line            n [expr]    Next, steps over\nsubs\nf filename  View source in file         <CR/Enter>  Repeat last n or s\n/pattern/ ?patt?   Search forw/backw    r           Return from\nsubroutine\nM           Show module versions        c [ln|sub]  Continue until\nposition\nDebugger controls:                       L           List break/watch/\nactions\no [...]     Set debugger options        t [expr]    Toggle trace\n[trace expr]\n<[<]|{[{]|>[>] [cmd] Do pre/post-prompt b [ln|event|sub] [cnd] Set\nbreakpoint\n! [N|pat]   Redo a previous command     B ln|*      Delete a/all\nbreakpoints\nH [-num]    Display last num commands   a [ln] cmd  Do cmd before line\n= [a val]   Define/list an alias        A ln|*      Delete a/all\nactions\nh [dbcmd]  Get help on command         w expr      Add a watch\nexpression\nh h         Complete help page          W expr|*    Delete a/all watch\nexprs\n|[|]dbcmd  Send output to pager        ![!] syscmd Run cmd in a\nsubprocess\nq or ^D     Quit                        R           Attempt a restart\nData Examination:     expr     Execute perl code, also see: s,n,t expr\nx|m expr       Evals expr in list context, dumps the result or lists\nmethods.\np expr         Print expression (uses script's current package).\nS [[!]pat]     List subroutine names [not] matching pattern\nV [Pk [Vars]]  List Variables in Package.  Vars can be ~pattern or\n!pattern.\nX [Vars]       Same as \"V currentpackage [Vars]\".\ny [n [Vars]]   List lexicals in higher scope <n>.  Vars same as V.\nFor more help, type h cmdletter, or run man perldebug for all docs.\n\nMore confusing options than you can shake a big stick at!  It's not as bad as it looks and\nit's very useful to know more about all of it, and fun too!\n\nThere's a couple of useful ones to know about straight away.  You wouldn't think we're using\nany libraries at all at the moment, but 'M' will show which modules are currently loaded, and\ntheir version number, while 'm' will show the methods, and 'S' shows all subroutines (by\npattern) as shown below.  'V' and 'X' show variables in the program by package scope and can\nbe constrained by pattern.\n\nDB<2>S str\ndumpvar::stringify\nstrict::bits\nstrict::import\nstrict::unimport\n\nUsing 'X' and cousins requires you not to use the type identifiers ($@%), just the 'name':\n\nDM<3>X ~err\nFileHandle(stderr) => fileno(2)\n\nRemember we're in our tiny program with a problem, we should have a look at where we are, and\nwhat our data looks like. First of all let's view some code at our present position (the\nfirst line of code in this case), via 'v':\n\nDB<4> v\n1       #!/usr/bin/perl\n2:      use strict;\n3\n4==>    my $key = 'welcome';\n5:      my %data = (\n6               'this' => qw(that),\n7               'tom' => qw(and jerry),\n8               'welcome' => q(Hello World),\n9               'zip' => q(welcome),\n10      );\n\nAt line number 4 is a helpful pointer, that tells you where you are now.  To see more code,\ntype 'v' again:\n\nDB<4> v\n8               'welcome' => q(Hello World),\n9               'zip' => q(welcome),\n10      );\n11:     my @data = keys %data;\n12:     print \"All OK\\n\" if grep($key, keys %data);\n13:     print \"$data{$key}\\n\";\n14:     print \"done: '$data{$key}'\\n\";\n15:     exit;\n\nAnd if you wanted to list line 5 again, type 'l 5', (note the space):\n\nDB<4> l 5\n5:      my %data = (\n\nIn this case, there's not much to see, but of course normally there's pages of stuff to wade\nthrough, and 'l' can be very useful.  To reset your view to the line we're about to execute,\ntype a lone period '.':\n\nDB<5> .\nmain::(./dataa:4):     my $key = 'welcome';\n\nThe line shown is the one that is about to be executed next, it hasn't happened yet.  So\nwhile we can print a variable with the letter 'p', at this point all we'd get is an empty\n(undefined) value back.  What we need to do is to step through the next executable statement\nwith an 's':\n\nDB<6> s\nmain::(./dataa:5):     my %data = (\nmain::(./dataa:6):             'this' => qw(that),\nmain::(./dataa:7):             'tom' => qw(and jerry),\nmain::(./dataa:8):             'welcome' => q(Hello World),\nmain::(./dataa:9):             'zip' => q(welcome),\nmain::(./dataa:10):    );\n\nNow we can have a look at that first ($key) variable:\n\nDB<7> p $key\nwelcome\n\nline 13 is where the action is, so let's continue down to there via the letter 'c', which by\nthe way, inserts a 'one-time-only' breakpoint at the given line or sub routine:\n\nDB<8> c 13\nAll OK\nmain::(./dataa:13):    print \"$data{$key}\\n\";\n\nWe've gone past our check (where 'All OK' was printed) and have stopped just before the meat\nof our task.  We could try to print out a couple of variables to see what is happening:\n\nDB<9> p $data{$key}\n\nNot much in there, lets have a look at our hash:\n\nDB<10> p %data\nHello Worldziptomandwelcomejerrywelcomethisthat\n\nDB<11> p keys %data\nHello Worldtomwelcomejerrythis\n\nWell, this isn't very easy to read, and using the helpful manual (h h), the 'x' command looks\npromising:\n\nDB<12> x %data\n0  'Hello World'\n1  'zip'\n2  'tom'\n3  'and'\n4  'welcome'\n5  undef\n6  'jerry'\n7  'welcome'\n8  'this'\n9  'that'\n\nThat's not much help, a couple of welcomes in there, but no indication of which are keys, and\nwhich are values, it's just a listed array dump and, in this case, not particularly helpful.\nThe trick here, is to use a reference to the data structure:\n\nDB<13> x \\%data\n0  HASH(0x8194bc4)\n'Hello World' => 'zip'\n'jerry' => 'welcome'\n'this' => 'that'\n'tom' => 'and'\n'welcome' => undef\n\nThe reference is truly dumped and we can finally see what we're dealing with.  Our quoting\nwas perfectly valid but wrong for our purposes, with 'and jerry' being treated as 2 separate\nwords rather than a phrase, thus throwing the evenly paired hash structure out of alignment.\n\nThe '-w' switch would have told us about this, had we used it at the start, and saved us a\nlot of trouble:\n\n> perl -w data\nOdd number of elements in hash assignment at ./data line 5.\n\nWe fix our quoting: 'tom' => q(and jerry), and run it again, this time we get our expected\noutput:\n\n> perl -w data\nHello World\n\nWhile we're here, take a closer look at the 'x' command, it's really useful and will merrily\ndump out nested references, complete objects, partial objects - just about whatever you throw\nat it:\n\nLet's make a quick object and x-plode it, first we'll start the debugger: it wants some form\nof input from STDIN, so we give it something non-committal, a zero:\n\n> perl -de 0\nDefault die handler restored.\n\nLoading DB routines from perl5db.pl version 1.07\nEditor support available.\n\nEnter h or `h h' for help, or `man perldebug' for more help.\n\nmain::(-e:1):   0\n\nNow build an on-the-fly object over a couple of lines (note the backslash):\n\nDB<1> $obj = bless({'uniqueid'=>'123', 'attr'=> \\\ncont:  {'col' => 'black', 'things' => [qw(this that etc)]}}, 'MYclass')\n\nAnd let's have a look at it:\n\nDB<2> x $obj\n0  MYclass=HASH(0x828ad98)\n'attr' => HASH(0x828ad68)\n'col' => 'black'\n'things' => ARRAY(0x828abb8)\n0  'this'\n1  'that'\n2  'etc'\n'uniqueid' => 123\nDB<3>\n\nUseful, huh?  You can eval nearly anything in there, and experiment with bits of code or\nregexes until the cows come home:\n\nDB<3> @data = qw(this that the other atheism leather theory scythe)\n\nDB<4> p 'saw -> '.($cnt += map { print \"\\t:\\t$\\n\" } grep(/the/, sort @data))\natheism\nleather\nother\nscythe\nthe\ntheory\nsaw -> 6\n\nIf you want to see the command History, type an 'H':\n\nDB<5> H\n4: p 'saw -> '.($cnt += map { print \"\\t:\\t$\\n\" } grep(/the/, sort @data))\n3: @data = qw(this that the other atheism leather theory scythe)\n2: x $obj\n1: $obj = bless({'uniqueid'=>'123', 'attr'=>\n{'col' => 'black', 'things' => [qw(this that etc)]}}, 'MYclass')\nDB<5>\n\nAnd if you want to repeat any previous command, use the exclamation: '!':\n\nDB<5> !4\np 'saw -> '.($cnt += map { print \"$\\n\" } grep(/the/, sort @data))\natheism\nleather\nother\nscythe\nthe\ntheory\nsaw -> 12\n\nFor more on references see perlref and perlreftut\n"
                },
                {
                    "name": "Stepping through code",
                    "content": "Here's a simple program which converts between Celsius and Fahrenheit, it too has a problem:\n\n#!/usr/bin/perl -w\nuse strict;\n\nmy $arg = $ARGV[0] || '-c20';\n\nif ($arg =~ /^\\-(c|f)((\\-|\\+)*\\d+(\\.\\d+)*)$/) {\nmy ($deg, $num) = ($1, $2);\nmy ($in, $out) = ($num, $num);\nif ($deg eq 'c') {\n$deg = 'f';\n$out = &c2f($num);\n} else {\n$deg = 'c';\n$out = &f2c($num);\n}\n$out = sprintf('%0.2f', $out);\n$out =~ s/^((\\-|\\+)*\\d+)\\.0+$/$1/;\nprint \"$out $deg\\n\";\n} else {\nprint \"Usage: $0 -[c|f] num\\n\";\n}\nexit;\n\nsub f2c {\nmy $f = shift;\nmy $c = 5 * $f - 32 / 9;\nreturn $c;\n}\n\nsub c2f {\nmy $c = shift;\nmy $f = 9 * $c / 5 + 32;\nreturn $f;\n}\n\nFor some reason, the Fahrenheit to Celsius conversion fails to return the expected output.\nThis is what it does:\n\n> temp -c0.72\n33.30 f\n\n> temp -f33.3\n162.94 c\n\nNot very consistent!  We'll set a breakpoint in the code manually and run it under the\ndebugger to see what's going on.  A breakpoint is a flag, to which the debugger will run\nwithout interruption, when it reaches the breakpoint, it will stop execution and offer a\nprompt for further interaction.  In normal use, these debugger commands are completely\nignored, and they are safe - if a little messy, to leave in production code.\n\nmy ($in, $out) = ($num, $num);\n$DB::single=2; # insert at line 9!\nif ($deg eq 'c')\n...\n\n> perl -d temp -f33.3\nDefault die handler restored.\n\nLoading DB routines from perl5db.pl version 1.07\nEditor support available.\n\nEnter h or `h h' for help, or `man perldebug' for more help.\n\nmain::(temp:4): my $arg = $ARGV[0] || '-c100';\n\nWe'll simply continue down to our pre-set breakpoint with a 'c':\n\nDB<1> c\nmain::(temp:10):                if ($deg eq 'c') {\n\nFollowed by a view command to see where we are:\n\nDB<1> v\n7:              my ($deg, $num) = ($1, $2);\n8:              my ($in, $out) = ($num, $num);\n9:              $DB::single=2;\n10==>           if ($deg eq 'c') {\n11:                     $deg = 'f';\n12:                     $out = &c2f($num);\n13              } else {\n14:                     $deg = 'c';\n15:                     $out = &f2c($num);\n16              }\n\nAnd a print to show what values we're currently using:\n\nDB<1> p $deg, $num\nf33.3\n\nWe can put another break point on any line beginning with a colon, we'll use line 17 as\nthat's just as we come out of the subroutine, and we'd like to pause there later on:\n\nDB<2> b 17\n\nThere's no feedback from this, but you can see what breakpoints are set by using the list 'L'\ncommand:\n\nDB<3> L\ntemp:\n17:            print \"$out $deg\\n\";\nbreak if (1)\n\nNote that to delete a breakpoint you use 'B'.\n\nNow we'll continue down into our subroutine, this time rather than by line number, we'll use\nthe subroutine name, followed by the now familiar 'v':\n\nDB<3> c f2c\nmain::f2c(temp:30):             my $f = shift;\n\nDB<4> v\n24:     exit;\n25\n26      sub f2c {\n27==>           my $f = shift;\n28:             my $c = 5 * $f - 32 / 9;\n29:             return $c;\n30      }\n31\n32      sub c2f {\n33:             my $c = shift;\n\nNote that if there was a subroutine call between us and line 29, and we wanted to single-step\nthrough it, we could use the 's' command, and to step over it we would use 'n' which would\nexecute the sub, but not descend into it for inspection.  In this case though, we simply\ncontinue down to line 29:\n\nDB<4> c 29\nmain::f2c(temp:29):             return $c;\n\nAnd have a look at the return value:\n\nDB<5> p $c\n162.944444444444\n\nThis is not the right answer at all, but the sum looks correct.  I wonder if it's anything to\ndo with operator precedence?  We'll try a couple of other possibilities with our sum:\n\nDB<6> p (5 * $f - 32 / 9)\n162.944444444444\n\nDB<7> p 5 * $f - (32 / 9)\n162.944444444444\n\nDB<8> p (5 * $f) - 32 / 9\n162.944444444444\n\nDB<9> p 5 * ($f - 32) / 9\n0.722222222222221\n\n:-) that's more like it!  Ok, now we can set our return variable and we'll return out of the\nsub with an 'r':\n\nDB<10> $c = 5 * ($f - 32) / 9\n\nDB<11> r\nscalar context return from main::f2c: 0.722222222222221\n\nLooks good, let's just continue off the end of the script:\n\nDB<12> c\n0.72 c\nDebugged program terminated.  Use q to quit or R to restart,\nuse O inhibitexit to avoid stopping after program termination,\nh q, h R or h O to get additional info.\n\nA quick fix to the offending line (insert the missing parentheses) in the actual program and\nwe're finished.\n"
                },
                {
                    "name": "Placeholder for a, w, t, T",
                    "content": "Actions, watch variables, stack traces etc.: on the TODO list.\n\na\n\nw\n\nt\n\nT\n"
                }
            ]
        },
        "REGULAR EXPRESSIONS": {
            "content": "Ever wanted to know what a regex looked like?  You'll need perl compiled with the DEBUGGING\nflag for this one:\n\n> perl -Dr -e '/^pe(a)*rl$/i'\nCompiling REx `^pe(a)*rl$'\nsize 17 first at 2\nrarest char\nat 0\n1: BOL(2)\n2: EXACTF <pe>(4)\n4: CURLYN[1] {0,32767}(14)\n6:   NOTHING(8)\n8:   EXACTF <a>(0)\n12:   WHILEM(0)\n13: NOTHING(14)\n14: EXACTF <rl>(16)\n16: EOL(17)\n17: END(0)\nfloating `'$ at 4..2147483647 (checking floating) stclass\n`EXACTF <pe>' anchored(BOL) minlen 4\nOmitting $` $& $' support.\n\nEXECUTING...\n\nFreeing REx: `^pe(a)*rl$'\n\nDid you really want to know? :-) For more gory details on getting regular expressions to\nwork, have a look at perlre, perlretut, and to decode the mysterious labels (BOL and CURLYN,\netc. above), see perldebguts.\n",
            "subsections": []
        },
        "OUTPUT TIPS": {
            "content": "To get all the output from your error log, and not miss any messages via helpful operating\nsystem buffering, insert a line like this, at the start of your script:\n\n$|=1;\n\nTo watch the tail of a dynamically growing logfile, (from the command line):\n\ntail -f $errorlog\n\nWrapping all die calls in a handler routine can be useful to see how, and from where, they're\nbeing called, perlvar has more information:\n\nBEGIN { $SIG{DIE} = sub { require Carp; Carp::confess(@) } }\n\nVarious useful techniques for the redirection of STDOUT and STDERR filehandles are explained\nin perlopentut and perlfaq8.\n",
            "subsections": []
        },
        "CGI": {
            "content": "Just a quick hint here for all those CGI programmers who can't figure out how on earth to get\npast that 'waiting for input' prompt, when running their CGI script from the command-line,\ntry something like this:\n\n> perl -d mycgi.pl -nodebug\n\nOf course CGI and perlfaq9 will tell you more.\n\nGUIs\nThe command line interface is tightly integrated with an emacs extension and there's a vi\ninterface too.\n\nYou don't have to do this all on the command line, though, there are a few GUI options out\nthere.  The nice thing about these is you can wave a mouse over a variable and a dump of its\ndata will appear in an appropriate window, or in a popup balloon, no more tiresome typing of\n'x $varname' :-)\n\nIn particular have a hunt around for the following:\n\nptkdb perlTK based wrapper for the built-in debugger\n\nddd data display debugger\n\nPerlDevKit and PerlBuilder are NT specific\n\nNB. (more info on these and others would be appreciated).\n",
            "subsections": []
        },
        "SUMMARY": {
            "content": "We've seen how to encourage good coding practices with use strict and -w.  We can run the\nperl debugger perl -d scriptname to inspect your data from within the perl debugger with the\np and x commands.  You can walk through your code, set breakpoints with b and step through\nthat code with s or n, continue with c and return from a sub with r.  Fairly intuitive stuff\nwhen you get down to it.\n\nThere is of course lots more to find out about, this has just scratched the surface.  The\nbest way to learn more is to use perldoc to find out more about the language, to read the on-\nline help (perldebug is probably the next place to go), and of course, experiment.\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "perldebug, perldebguts, perl5db.pl, perldiag, perlrun\n",
            "subsections": []
        },
        "AUTHOR": {
            "content": "Richard Foley <richard.foley@rfi.net> Copyright (c) 2000\n",
            "subsections": []
        },
        "CONTRIBUTORS": {
            "content": "Various people have made helpful suggestions and contributions, in particular:\n\nRonald J Kimball <rjk@linguist.dartmouth.edu>\n\nHugo van der Sanden <hv@crypt0.demon.co.uk>\n\nPeter Scott <Peter@PSDT.com>\n\n\n\nperl v5.34.0                                 2025-07-25                                PERLDEBTUT(1)",
            "subsections": []
        }
    },
    "summary": "perldebtut - Perl debugging tutorial",
    "flags": [],
    "examples": [],
    "see_also": []
}