1PERLDEBTUT(1)          Perl Programmers Reference Guide          PERLDEBTUT(1)
2
3
4

NAME

6       perldebtut - Perl debugging tutorial
7

DESCRIPTION

9       A (very) lightweight introduction in the use of the perl debugger, and
10       a pointer to existing, deeper sources of information on the subject of
11       debugging perl programs.
12
13       There's an extraordinary number of people out there who don't appear to
14       know anything about using the perl debugger, though they use the
15       language every day.  This is for them.
16

use strict

18       First of all, there's a few things you can do to make your life a lot
19       more straightforward when it comes to debugging perl programs, without
20       using the debugger at all.  To demonstrate, here's a simple script,
21       named "hello", with a problem:
22
23               #!/usr/bin/perl
24
25               $var1 = 'Hello World'; # always wanted to do that :-)
26               $var2 = "$varl\n";
27
28               print $var2;
29               exit;
30
31       While this compiles and runs happily, it probably won't do what's
32       expected, namely it doesn't print "Hello World\n" at all;  It will on
33       the other hand do exactly what it was told to do, computers being a bit
34       that way inclined.  That is, it will print out a newline character, and
35       you'll get what looks like a blank line.  It looks like there's 2
36       variables when (because of the typo) there's really 3:
37
38               $var1 = 'Hello World';
39               $varl = undef;
40               $var2 = "\n";
41
42       To catch this kind of problem, we can force each variable to be
43       declared before use by pulling in the strict module, by putting 'use
44       strict;' after the first line of the script.
45
46       Now when you run it, perl complains about the 3 undeclared variables
47       and we get four error messages because one variable is referenced
48       twice:
49
50        Global symbol "$var1" requires explicit package name at ./t1 line 4.
51        Global symbol "$var2" requires explicit package name at ./t1 line 5.
52        Global symbol "$varl" requires explicit package name at ./t1 line 5.
53        Global symbol "$var2" requires explicit package name at ./t1 line 7.
54        Execution of ./hello aborted due to compilation errors.
55
56       Luvverly! and to fix this we declare all variables explicitly and now
57       our script looks like this:
58
59               #!/usr/bin/perl
60               use strict;
61
62               my $var1 = 'Hello World';
63               my $varl = undef;
64               my $var2 = "$varl\n";
65
66               print $var2;
67               exit;
68
69       We then do (always a good idea) a syntax check before we try to run it
70       again:
71
72               > perl -c hello
73               hello syntax OK
74
75       And now when we run it, we get "\n" still, but at least we know why.
76       Just getting this script to compile has exposed the '$varl' (with the
77       letter 'l') variable, and simply changing $varl to $var1 solves the
78       problem.
79

Looking at data and -w and v

81       Ok, but how about when you want to really see your data, what's in that
82       dynamic variable, just before using it?
83
84               #!/usr/bin/perl
85               use strict;
86
87               my $key = 'welcome';
88               my %data = (
89                       'this' => qw(that),
90                       'tom' => qw(and jerry),
91                       'welcome' => q(Hello World),
92                       'zip' => q(welcome),
93               );
94               my @data = keys %data;
95
96               print "$data{$key}\n";
97               exit;
98
99       Looks OK, after it's been through the syntax check (perl -c
100       scriptname), we run it and all we get is a blank line again!  Hmmmm.
101
102       One common debugging approach here, would be to liberally sprinkle a
103       few print statements, to add a check just before we print out our data,
104       and another just after:
105
106               print "All OK\n" if grep($key, keys %data);
107               print "$data{$key}\n";
108               print "done: '$data{$key}'\n";
109
110       And try again:
111
112               > perl data
113               All OK
114
115               done: ''
116
117       After much staring at the same piece of code and not seeing the wood
118       for the trees for some time, we get a cup of coffee and try another
119       approach.  That is, we bring in the cavalry by giving perl the '-d'
120       switch on the command line:
121
122               > perl -d data
123               Default die handler restored.
124
125               Loading DB routines from perl5db.pl version 1.07
126               Editor support available.
127
128               Enter h or `h h' for help, or `man perldebug' for more help.
129
130               main::(./data:4):     my $key = 'welcome';
131
132       Now, what we've done here is to launch the built-in perl debugger on
133       our script.  It's stopped at the first line of executable code and is
134       waiting for input.
135
136       Before we go any further, you'll want to know how to quit the debugger:
137       use just the letter 'q', not the words 'quit' or 'exit':
138
139               DB<1> q
140               >
141
142       That's it, you're back on home turf again.
143

help

145       Fire the debugger up again on your script and we'll look at the help
146       menu.  There's a couple of ways of calling help: a simple 'h' will get
147       the summary help list, '|h' (pipe-h) will pipe the help through your
148       pager (which is (probably 'more' or 'less'), and finally, 'h h'
149       (h-space-h) will give you the entire help screen.  Here is the summary
150       page:
151
152       D1h
153
154        List/search source lines:               Control script execution:
155         l [ln|sub]  List source code            T           Stack trace
156         - or .      List previous/current line  s [expr]    Single step
157                                                                      [in expr]
158         v [line]    View around line            n [expr]    Next, steps over
159                                                                           subs
160         f filename  View source in file         <CR/Enter>  Repeat last n or s
161         /pattern/ ?patt?   Search forw/backw    r           Return from
162                                                                     subroutine
163         M           Show module versions        c [ln|sub]  Continue until
164                                                                       position
165        Debugger controls:                       L           List break/watch/
166                                                                        actions
167         o [...]     Set debugger options        t [expr]    Toggle trace
168                                                                   [trace expr]
169         <[<]|{[{]|>[>] [cmd] Do pre/post-prompt b [ln|event|sub] [cnd] Set
170                                                                     breakpoint
171         ! [N|pat]   Redo a previous command     B ln|*      Delete a/all
172                                                                    breakpoints
173         H [-num]    Display last num commands   a [ln] cmd  Do cmd before line
174         = [a val]   Define/list an alias        A ln|*      Delete a/all
175                                                                        actions
176         h [db_cmd]  Get help on command         w expr      Add a watch
177                                                                     expression
178         h h         Complete help page          W expr|*    Delete a/all watch
179                                                                          exprs
180         |[|]db_cmd  Send output to pager        ![!] syscmd Run cmd in a
181                                                                     subprocess
182         q or ^D     Quit                        R           Attempt a restart
183        Data Examination:     expr     Execute perl code, also see: s,n,t expr
184         x|m expr       Evals expr in list context, dumps the result or lists
185                                                                       methods.
186         p expr         Print expression (uses script's current package).
187         S [[!]pat]     List subroutine names [not] matching pattern
188         V [Pk [Vars]]  List Variables in Package.  Vars can be ~pattern or
189                                                                      !pattern.
190         X [Vars]       Same as "V current_package [Vars]".
191         y [n [Vars]]   List lexicals in higher scope <n>.  Vars same as V.
192        For more help, type h cmd_letter, or run man perldebug for all docs.
193
194       More confusing options than you can shake a big stick at!  It's not as
195       bad as it looks and it's very useful to know more about all of it, and
196       fun too!
197
198       There's a couple of useful ones to know about straight away.  You
199       wouldn't think we're using any libraries at all at the moment, but 'M'
200       will show which modules are currently loaded, and their version number,
201       while 'm' will show the methods, and 'S' shows all subroutines (by
202       pattern) as shown below.  'V' and 'X' show variables in the program by
203       package scope and can be constrained by pattern.
204
205               DB<2>S str
206               dumpvar::stringify
207               strict::bits
208               strict::import
209               strict::unimport
210
211       Using 'X' and cousins requires you not to use the type identifiers
212       ($@%), just the 'name':
213
214               DM<3>X ~err
215               FileHandle(stderr) => fileno(2)
216
217       Remember we're in our tiny program with a problem, we should have a
218       look at where we are, and what our data looks like. First of all let's
219       view some code at our present position (the first line of code in this
220       case), via 'v':
221
222               DB<4> v
223               1       #!/usr/bin/perl
224               2:      use strict;
225               3
226               4==>    my $key = 'welcome';
227               5:      my %data = (
228               6               'this' => qw(that),
229               7               'tom' => qw(and jerry),
230               8               'welcome' => q(Hello World),
231               9               'zip' => q(welcome),
232               10      );
233
234       At line number 4 is a helpful pointer, that tells you where you are
235       now.  To see more code, type 'v' again:
236
237               DB<4> v
238               8               'welcome' => q(Hello World),
239               9               'zip' => q(welcome),
240               10      );
241               11:     my @data = keys %data;
242               12:     print "All OK\n" if grep($key, keys %data);
243               13:     print "$data{$key}\n";
244               14:     print "done: '$data{$key}'\n";
245               15:     exit;
246
247       And if you wanted to list line 5 again, type 'l 5', (note the space):
248
249               DB<4> l 5
250               5:      my %data = (
251
252       In this case, there's not much to see, but of course normally there's
253       pages of stuff to wade through, and 'l' can be very useful.  To reset
254       your view to the line we're about to execute, type a lone period '.':
255
256               DB<5> .
257               main::(./data_a:4):     my $key = 'welcome';
258
259       The line shown is the one that is about to be executed next, it hasn't
260       happened yet.  So while we can print a variable with the letter 'p', at
261       this point all we'd get is an empty (undefined) value back.  What we
262       need to do is to step through the next executable statement with an
263       's':
264
265               DB<6> s
266               main::(./data_a:5):     my %data = (
267               main::(./data_a:6):             'this' => qw(that),
268               main::(./data_a:7):             'tom' => qw(and jerry),
269               main::(./data_a:8):             'welcome' => q(Hello World),
270               main::(./data_a:9):             'zip' => q(welcome),
271               main::(./data_a:10):    );
272
273       Now we can have a look at that first ($key) variable:
274
275               DB<7> p $key
276               welcome
277
278       line 13 is where the action is, so let's continue down to there via the
279       letter 'c', which by the way, inserts a 'one-time-only' breakpoint at
280       the given line or sub routine:
281
282               DB<8> c 13
283               All OK
284               main::(./data_a:13):    print "$data{$key}\n";
285
286       We've gone past our check (where 'All OK' was printed) and have stopped
287       just before the meat of our task.  We could try to print out a couple
288       of variables to see what is happening:
289
290               DB<9> p $data{$key}
291
292       Not much in there, lets have a look at our hash:
293
294               DB<10> p %data
295               Hello Worldziptomandwelcomejerrywelcomethisthat
296
297               DB<11> p keys %data
298               Hello Worldtomwelcomejerrythis
299
300       Well, this isn't very easy to read, and using the helpful manual (h h),
301       the 'x' command looks promising:
302
303               DB<12> x %data
304               0  'Hello World'
305               1  'zip'
306               2  'tom'
307               3  'and'
308               4  'welcome'
309               5  undef
310               6  'jerry'
311               7  'welcome'
312               8  'this'
313               9  'that'
314
315       That's not much help, a couple of welcomes in there, but no indication
316       of which are keys, and which are values, it's just a listed array dump
317       and, in this case, not particularly helpful.  The trick here, is to use
318       a reference to the data structure:
319
320               DB<13> x \%data
321               0  HASH(0x8194bc4)
322                  'Hello World' => 'zip'
323                  'jerry' => 'welcome'
324                  'this' => 'that'
325                  'tom' => 'and'
326                  'welcome' => undef
327
328       The reference is truly dumped and we can finally see what we're dealing
329       with.  Our quoting was perfectly valid but wrong for our purposes, with
330       'and jerry' being treated as 2 separate words rather than a phrase,
331       thus throwing the evenly paired hash structure out of alignment.
332
333       The '-w' switch would have told us about this, had we used it at the
334       start, and saved us a lot of trouble:
335
336               > perl -w data
337               Odd number of elements in hash assignment at ./data line 5.
338
339       We fix our quoting: 'tom' => q(and jerry), and run it again, this time
340       we get our expected output:
341
342               > perl -w data
343               Hello World
344
345       While we're here, take a closer look at the 'x' command, it's really
346       useful and will merrily dump out nested references, complete objects,
347       partial objects - just about whatever you throw at it:
348
349       Let's make a quick object and x-plode it, first we'll start the
350       debugger: it wants some form of input from STDIN, so we give it
351       something non-committal, a zero:
352
353        > perl -de 0
354        Default die handler restored.
355
356        Loading DB routines from perl5db.pl version 1.07
357        Editor support available.
358
359        Enter h or `h h' for help, or `man perldebug' for more help.
360
361        main::(-e:1):   0
362
363       Now build an on-the-fly object over a couple of lines (note the
364       backslash):
365
366        DB<1> $obj = bless({'unique_id'=>'123', 'attr'=> \
367        cont:  {'col' => 'black', 'things' => [qw(this that etc)]}}, 'MY_class')
368
369       And let's have a look at it:
370
371               DB<2> x $obj
372        0  MY_class=HASH(0x828ad98)
373                       'attr' => HASH(0x828ad68)
374               'col' => 'black'
375               'things' => ARRAY(0x828abb8)
376                       0  'this'
377                       1  'that'
378                       2  'etc'
379                       'unique_id' => 123
380               DB<3>
381
382       Useful, huh?  You can eval nearly anything in there, and experiment
383       with bits of code or regexes until the cows come home:
384
385        DB<3> @data = qw(this that the other atheism leather theory scythe)
386
387        DB<4> p 'saw -> '.($cnt += map { print "\t:\t$_\n" } grep(/the/, sort @data))
388        atheism
389        leather
390        other
391        scythe
392        the
393        theory
394        saw -> 6
395
396       If you want to see the command History, type an 'H':
397
398        DB<5> H
399        4: p 'saw -> '.($cnt += map { print "\t:\t$_\n" } grep(/the/, sort @data))
400        3: @data = qw(this that the other atheism leather theory scythe)
401        2: x $obj
402        1: $obj = bless({'unique_id'=>'123', 'attr'=>
403        {'col' => 'black', 'things' => [qw(this that etc)]}}, 'MY_class')
404        DB<5>
405
406       And if you want to repeat any previous command, use the exclamation:
407       '!':
408
409        DB<5> !4
410        p 'saw -> '.($cnt += map { print "$_\n" } grep(/the/, sort @data))
411        atheism
412        leather
413        other
414        scythe
415        the
416        theory
417        saw -> 12
418
419       For more on references see perlref and perlreftut
420

Stepping through code

422       Here's a simple program which converts between Celsius and Fahrenheit,
423       it too has a problem:
424
425        #!/usr/bin/perl -w
426        use strict;
427
428        my $arg = $ARGV[0] || '-c20';
429
430        if ($arg =~ /^\-(c|f)((\-|\+)*\d+(\.\d+)*)$/) {
431               my ($deg, $num) = ($1, $2);
432               my ($in, $out) = ($num, $num);
433               if ($deg eq 'c') {
434                       $deg = 'f';
435                       $out = &c2f($num);
436               } else {
437                       $deg = 'c';
438                       $out = &f2c($num);
439               }
440               $out = sprintf('%0.2f', $out);
441               $out =~ s/^((\-|\+)*\d+)\.0+$/$1/;
442               print "$out $deg\n";
443        } else {
444               print "Usage: $0 -[c|f] num\n";
445        }
446        exit;
447
448        sub f2c {
449               my $f = shift;
450               my $c = 5 * $f - 32 / 9;
451               return $c;
452        }
453
454        sub c2f {
455               my $c = shift;
456               my $f = 9 * $c / 5 + 32;
457               return $f;
458        }
459
460       For some reason, the Fahrenheit to Celsius conversion fails to return
461       the expected output.  This is what it does:
462
463        > temp -c0.72
464        33.30 f
465
466        > temp -f33.3
467        162.94 c
468
469       Not very consistent!  We'll set a breakpoint in the code manually and
470       run it under the debugger to see what's going on.  A breakpoint is a
471       flag, to which the debugger will run without interruption, when it
472       reaches the breakpoint, it will stop execution and offer a prompt for
473       further interaction.  In normal use, these debugger commands are
474       completely ignored, and they are safe - if a little messy, to leave in
475       production code.
476
477               my ($in, $out) = ($num, $num);
478               $DB::single=2; # insert at line 9!
479               if ($deg eq 'c')
480                       ...
481
482               > perl -d temp -f33.3
483               Default die handler restored.
484
485               Loading DB routines from perl5db.pl version 1.07
486               Editor support available.
487
488               Enter h or `h h' for help, or `man perldebug' for more help.
489
490               main::(temp:4): my $arg = $ARGV[0] || '-c100';
491
492       We'll simply continue down to our pre-set breakpoint with a 'c':
493
494               DB<1> c
495               main::(temp:10):                if ($deg eq 'c') {
496
497       Followed by a view command to see where we are:
498
499               DB<1> v
500               7:              my ($deg, $num) = ($1, $2);
501               8:              my ($in, $out) = ($num, $num);
502               9:              $DB::single=2;
503               10==>           if ($deg eq 'c') {
504               11:                     $deg = 'f';
505               12:                     $out = &c2f($num);
506               13              } else {
507               14:                     $deg = 'c';
508               15:                     $out = &f2c($num);
509               16              }
510
511       And a print to show what values we're currently using:
512
513               DB<1> p $deg, $num
514               f33.3
515
516       We can put another break point on any line beginning with a colon,
517       we'll use line 17 as that's just as we come out of the subroutine, and
518       we'd like to pause there later on:
519
520               DB<2> b 17
521
522       There's no feedback from this, but you can see what breakpoints are set
523       by using the list 'L' command:
524
525               DB<3> L
526               temp:
527                       17:            print "$out $deg\n";
528                       break if (1)
529
530       Note that to delete a breakpoint you use 'B'.
531
532       Now we'll continue down into our subroutine, this time rather than by
533       line number, we'll use the subroutine name, followed by the now
534       familiar 'v':
535
536               DB<3> c f2c
537               main::f2c(temp:30):             my $f = shift;
538
539               DB<4> v
540               24:     exit;
541               25
542               26      sub f2c {
543               27==>           my $f = shift;
544               28:             my $c = 5 * $f - 32 / 9;
545               29:             return $c;
546               30      }
547               31
548               32      sub c2f {
549               33:             my $c = shift;
550
551       Note that if there was a subroutine call between us and line 29, and we
552       wanted to single-step through it, we could use the 's' command, and to
553       step over it we would use 'n' which would execute the sub, but not
554       descend into it for inspection.  In this case though, we simply
555       continue down to line 29:
556
557               DB<4> c 29
558               main::f2c(temp:29):             return $c;
559
560       And have a look at the return value:
561
562               DB<5> p $c
563               162.944444444444
564
565       This is not the right answer at all, but the sum looks correct.  I
566       wonder if it's anything to do with operator precedence?  We'll try a
567       couple of other possibilities with our sum:
568
569               DB<6> p (5 * $f - 32 / 9)
570               162.944444444444
571
572               DB<7> p 5 * $f - (32 / 9)
573               162.944444444444
574
575               DB<8> p (5 * $f) - 32 / 9
576               162.944444444444
577
578               DB<9> p 5 * ($f - 32) / 9
579               0.722222222222221
580
581       :-) that's more like it!  Ok, now we can set our return variable and
582       we'll return out of the sub with an 'r':
583
584               DB<10> $c = 5 * ($f - 32) / 9
585
586               DB<11> r
587               scalar context return from main::f2c: 0.722222222222221
588
589       Looks good, let's just continue off the end of the script:
590
591               DB<12> c
592               0.72 c
593               Debugged program terminated.  Use q to quit or R to restart,
594               use O inhibit_exit to avoid stopping after program termination,
595               h q, h R or h O to get additional info.
596
597       A quick fix to the offending line (insert the missing parentheses) in
598       the actual program and we're finished.
599

Placeholder for a, w, t, T

601       Actions, watch variables, stack traces etc.: on the TODO list.
602
603               a
604
605               w
606
607               t
608
609               T
610

REGULAR EXPRESSIONS

612       Ever wanted to know what a regex looked like?  You'll need perl
613       compiled with the DEBUGGING flag for this one:
614
615         > perl -Dr -e '/^pe(a)*rl$/i'
616         Compiling REx `^pe(a)*rl$'
617         size 17 first at 2
618         rarest char
619          at 0
620            1: BOL(2)
621            2: EXACTF <pe>(4)
622            4: CURLYN[1] {0,32767}(14)
623            6:   NOTHING(8)
624            8:   EXACTF <a>(0)
625           12:   WHILEM(0)
626           13: NOTHING(14)
627           14: EXACTF <rl>(16)
628           16: EOL(17)
629           17: END(0)
630         floating `'$ at 4..2147483647 (checking floating) stclass
631           `EXACTF <pe>' anchored(BOL) minlen 4
632         Omitting $` $& $' support.
633
634         EXECUTING...
635
636         Freeing REx: `^pe(a)*rl$'
637
638       Did you really want to know? :-) For more gory details on getting
639       regular expressions to work, have a look at perlre, perlretut, and to
640       decode the mysterious labels (BOL and CURLYN, etc. above), see
641       perldebguts.
642

OUTPUT TIPS

644       To get all the output from your error log, and not miss any messages
645       via helpful operating system buffering, insert a line like this, at the
646       start of your script:
647
648               $|=1;
649
650       To watch the tail of a dynamically growing logfile, (from the command
651       line):
652
653               tail -f $error_log
654
655       Wrapping all die calls in a handler routine can be useful to see how,
656       and from where, they're being called, perlvar has more information:
657
658           BEGIN { $SIG{__DIE__} = sub { require Carp; Carp::confess(@_) } }
659
660       Various useful techniques for the redirection of STDOUT and STDERR
661       filehandles are explained in perlopentut and perlfaq8.
662

CGI

664       Just a quick hint here for all those CGI programmers who can't figure
665       out how on earth to get past that 'waiting for input' prompt, when
666       running their CGI script from the command-line, try something like
667       this:
668
669               > perl -d my_cgi.pl -nodebug
670
671       Of course CGI and perlfaq9 will tell you more.
672

GUIs

674       The command line interface is tightly integrated with an emacs
675       extension and there's a vi interface too.
676
677       You don't have to do this all on the command line, though, there are a
678       few GUI options out there.  The nice thing about these is you can wave
679       a mouse over a variable and a dump of its data will appear in an
680       appropriate window, or in a popup balloon, no more tiresome typing of
681       'x $varname' :-)
682
683       In particular have a hunt around for the following:
684
685       ptkdb perlTK based wrapper for the built-in debugger
686
687       ddd data display debugger
688
689       PerlDevKit and PerlBuilder are NT specific
690
691       NB. (more info on these and others would be appreciated).
692

SUMMARY

694       We've seen how to encourage good coding practices with use strict and
695       -w.  We can run the perl debugger perl -d scriptname to inspect your
696       data from within the perl debugger with the p and x commands.  You can
697       walk through your code, set breakpoints with b and step through that
698       code with s or n, continue with c and return from a sub with r.  Fairly
699       intuitive stuff when you get down to it.
700
701       There is of course lots more to find out about, this has just scratched
702       the surface.  The best way to learn more is to use perldoc to find out
703       more about the language, to read the on-line help (perldebug is
704       probably the next place to go), and of course, experiment.
705

SEE ALSO

707       perldebug, perldebguts, perldiag, perlrun
708

AUTHOR

710       Richard Foley <richard.foley@rfi.net> Copyright (c) 2000
711

CONTRIBUTORS

713       Various people have made helpful suggestions and contributions, in
714       particular:
715
716       Ronald J Kimball <rjk@linguist.dartmouth.edu>
717
718       Hugo van der Sanden <hv@crypt0.demon.co.uk>
719
720       Peter Scott <Peter@PSDT.com>
721
722
723
724perl v5.28.2                      2018-03-01                     PERLDEBTUT(1)
Impressum