Update Changes.
[p5sagit/p5-mst-13.2.git] / pod / perldebtut.pod
1 =head1 NAME
2
3 perldebtut - Perl debugging tutorial
4
5 =head1 DESCRIPTION
6
7 A (very) lightweight introduction in the use of the perl debugger, and a
8 pointer to existing, deeper sources of information on the subject of debugging
9 perl programs. 
10
11 There's an extraordinary number of people out there who don't appear to know
12 anything about using the perl debugger, though they use the language every
13 day.  
14 This is for them.  
15
16
17 =head1 use strict
18
19 There's a few things you can do to make your life a lot more straightforward
20 when it comes to debugging perl programs.  To demonstrate, here's a simple
21 script 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 expected,
32 namely it doesn't print "Hello World\n" at all;  It will on the other hand do
33 exactly what it was told to do, computers being a bit that way inclined.  That
34 is, it will print out a newline character, and you'll get what looks like a
35 blank line.  It looks like there's 2 variables when (because of the typo)
36 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 declared
43 before use by pulling in the strict module, by putting 'use strict;' after the
44 first line of the script.
45
46 Now when you run it, perl complains about the 3 undeclared variables and we
47 get four error messages because one variable is referenced twice:
48  
49  Global symbol "$var1" requires explicit package name at ./t1 line 4.
50  Global symbol "$var2" requires explicit package name at ./t1 line 5.
51  Global symbol "$varl" requires explicit package name at ./t1 line 5.
52  Global symbol "$var2" requires explicit package name at ./t1 line 7.
53  Execution of ./t1 aborted due to compilation errors.     
54
55 Luvverly! and to fix this we declare all variables explicitly and now our
56 script looks like this: 
57
58         #!/usr/bin/perl
59         use strict;
60         
61         my $var1 = 'Hello World';
62         my $varl = '';
63         my $var2 = "$varl\n";
64         
65         print $var2; 
66         exit;
67
68 We then do (always a good idea) a syntax check before we try to run it again:
69
70         > perl -c hello
71         hello syntax OK 
72
73 And now when we run it, we get "\n" still, but at least we know why.  Just
74 getting this script to compile has exposed the '$varl' (with the letter 'l)
75 variable, and simply changing $varl to $var1 solves the problem.
76
77
78 =head1 Looking at data and -w
79
80 Ok, but how about when you want to really see your data, what's in that
81 dynamic variable, just before using it?
82
83         #!/usr/bin/perl 
84         use strict;
85
86         my $key = 'welcome';
87         my %data = (
88                 'this' => qw(that), 
89                 'tom' => qw(and jerry),
90                 'welcome' => q(Hello World),
91                 'zip' => q(welcome),
92         );
93         my @data = keys %data;
94
95         print "$data{$key}\n";
96         exit;                               
97
98 Looks OK, after it's been through the syntax check (perl -c scriptname), we
99 run it and all we get is a blank line again!  Hmmmm.
100  
101 One common debugging approach here, would be to liberally sprinkle a few print
102 statements, to add a check just before we print out our data, and another just
103 after:
104
105         print "All OK\n" if grep($key, keys %data);
106         print "$data{$key}\n";
107         print "done: '$data{$key}'\n";
108
109 And try again:
110         
111         > perl data
112         All OK     
113         
114         done: ''
115
116 After much staring at the same piece of code and not seeing the wood for the
117 trees for some time, we get a cup of coffee and try another approach.  That
118 is, we bring in the cavalry by giving perl the C<-d> switch on the command
119 line:
120
121         > perl -d data 
122         Default die handler restored.
123
124         Loading DB routines from perl5db.pl version 1.07
125         Editor support available.
126
127         Enter h or `h h' for help, or `man perldebug' for more help.
128
129         main::(./data:4):     my $key = 'welcome';   
130
131 Now, what we've done here is to launch the built-in perl debugger on our
132 script.  It's stopped at the first line of executable code and is waiting for
133 input.
134
135 Before we go any further, you'll want to know how to quit the debugger: use
136 just the letter 'q', not the words 'quit' or 'exit':
137
138         DB<1> q
139         >
140         
141 That's it, you're back on home turf again.
142
143 Fire the debugger up again on your script and we'll look at the help menu. 
144 There's a couple of ways of calling help: a simple 'h' will get you a long
145 scrolled list of help, '|h' (pipe-h) will pipe the help through your pager
146 ('more' or 'less' probably), and finally, 'h h' (h-space-h) will give you a
147 helpful mini-screen snapshot:
148
149         DB<1> h h
150         List/search source lines:               Control script execution:
151         l [ln|sub]  List source code            T           Stack trace
152         - or .      List previous/current line  s [expr]    Single step [in expr]
153         w [line]    List around line            n [expr]    Next, steps over subs
154         f filename  View source in file         <CR/Enter>  Repeat last n or s
155         /pattern/ ?patt?   Search forw/backw    r           Return from subroutine
156         v           Show versions of modules    c [ln|sub]  Continue until position
157         Debugger controls:                        L           List
158 break/watch/actions
159         O [...]     Set debugger options        t [expr]    Toggle trace [trace expr]
160         <[<]|{[{]|>[>] [cmd] Do pre/post-prompt b [ln|event|sub] [cnd] Set breakpoint
161         ! [N|pat]   Redo a previous command     d [ln] or D Delete a/all breakpoints
162         H [-num]    Display last num commands   a [ln] cmd  Do cmd before line
163         = [a val]   Define/list an alias        W expr      Add a watch expression
164         h [db_cmd]  Get help on command         A or W      Delete all actions/watch
165         |[|]db_cmd  Send output to pager        ![!] syscmd Run cmd in a subprocess
166         q or ^D     Quit                        R           Attempt a restart
167         Data Examination:       expr     Execute perl code, also see: s,n,t expr
168         x|m expr      Evals expr in array context, dumps the result or lists methods.
169         p expr        Print expression (uses script's current package).
170         S [[!]pat]    List subroutine names [not] matching pattern
171         V [Pk [Vars]] List Variables in Package.  Vars can be ~pattern or !pattern.
172         X [Vars]      Same as "V current_package [Vars]".
173         For more help, type h cmd_letter, or run man perldebug for all docs.       
174         
175 More confusing options than you can shake a big stick at!  It's not as bad as
176 it looks and it's very useful to know more about all of it, and fun too!
177
178 There's a couple of useful ones to know about straight away: 
179 You wouldn't think we're using any libraries at all at the moment, but 'v'
180 will show which modules are currently loaded, by the debugger as well your
181 script.  'V' and 'X' show variables in the program by package scope and can be
182 constrained by pattern.  'S' shows all subroutines (by pattern):
183
184         DB<2>S str 
185         dumpvar::stringify
186         strict::bits
187         strict::import
188         strict::unimport  
189         
190 Remember we're in our tiny program with a problem, we want to have a look at
191 where we are, and what our data looks like. First of all let's have a window
192 on our present position (the first line of code), via the letter 'w':
193
194         DB<3> w
195         1       #!/usr/bin/perl
196         2:      use strict;
197         3
198         4==>    my $key = 'welcome';
199         5:      my %data = (
200         6               'this' => qw(that),
201         7               'tom' => qw(and jerry),
202         8               'welcome' => q(Hello World),
203         9               'zip' => q(welcome),
204         10      );                                 
205
206 At line number 4 is a helpful pointer, that tells you where you are now.  To
207 see more code, type 'w' again:
208         
209         DB<3> w
210         8               'welcome' => q(Hello World),
211         9               'zip' => q(welcome),
212         10      );
213         11:     my @data = keys %data;
214         12:     print "All OK\n" if grep($key, keys %data);
215         13:     print "$data{$key}\n";
216         14:     print "done: '$data{$key}'\n";
217         15:     exit;      
218
219 And if you wanted to list line 5 again, type 'l 5', note the space:
220
221         DB<4> l 5
222         5:      my %data = (
223         
224 In this case, there's not much to see, but of course normally there's pages of
225 stuff to wade through.  To reset your view to the line we're about to execute,
226 type a lone period '.':
227
228         DB<6> .
229         main::(./data_a:4):     my $key = 'welcome';  
230         
231 The line shown is the one that is about to be executed B<next>, it hasn't
232 happened yet.  So while we can print a variable with the letter 'p', at this
233 point all we'd get is an empty (undefined) value back.  What we need to do is
234 to step to the next executable statement with an 's':
235         
236         DB<6> s
237         main::(./data_a:5):     my %data = (
238         main::(./data_a:6):             'this' => qw(that),
239         main::(./data_a:7):             'tom' => qw(and jerry),
240         main::(./data_a:8):             'welcome' => q(Hello World),
241         main::(./data_a:9):             'zip' => q(welcome),
242         main::(./data_a:10):    );   
243
244 Now we can have a look at that first ($key) variable:
245
246         DB<7> p $key 
247         welcome 
248
249 line 13 is where the action is, so let's continue down to there via the letter
250 'c':
251
252         DB<8> c 13
253         All OK
254         main::(./data_a:13):    print "$data{$key}\n";
255         
256 We've gone past our check (where 'All OK' was printed) and have stopped just
257 before the meat of our task.  We could try to print out a couple of variables
258 to see what is happening:
259
260         DB<9> p $data{$key}
261         
262 Nothing!        
263         
264         DB<10> p %data
265         Hello Worldziptomandwelcomejerrywelcomethisthat 
266
267         DB<11> p keys %data
268         Hello Worldtomwelcomejerrythis  
269         
270 Reading the helpful manual (h h), the 'x' command looks promising:
271
272         DB<12> x %data
273         0  'Hello World'
274         1  'zip'
275         2  'tom'
276         3  'and'
277         4  'welcome'
278         5  undef
279         6  'jerry'
280         7  'welcome'
281         8  'this'
282         9  'that'     
283
284 That's not much help, a couple of welcome's in there, but no indication of
285 which are keys, and which are values, it's just a straight array dump and, in
286 this case, not particularly helpful.  The trick here, is to use a B<reference>
287 to the data structure:
288
289         DB<13> x \%data
290         0  HASH(0x8194bc4)
291            'Hello World' => 'zip'
292            'jerry' => 'welcome'
293            'this' => 'that'
294            'tom' => 'and'
295            'welcome' => undef  
296
297 The reference is truly dumped and we can finally see what we're dealing with. 
298 Our quoting was perfectly valid but wrong for our purposes, with 'and jerry'
299 being treated as 2 separate words rather than a phrase, thus throwing the
300 evenly paired hash structure out of alignment.
301
302 The '-w' switch would have told us about this, had we used it at the start,
303 and saved us a lot of trouble: 
304
305         > perl -w data
306         Odd number of elements in hash assignment at ./data line 5.    
307
308 We fix our quoting: 'tom' => q(and jerry), and run it again, this time we get
309 our expected output:
310
311         > perl -w data
312         Hello World
313
314
315 While we're here, take a closer look at the 'x' command, it's really useful
316 and will merrily dump out nested references, complete objects, partial objects
317 - justabout whatever you throw at it:
318
319 Let's make a quick object and x-plode it, first we'll start the the debugger:
320 it wants some form of input from STDIN, so we give it something non-commital,
321 a zero:
322
323         > perl -de 0
324         Default die handler restored.
325
326         Loading DB routines from perl5db.pl version 1.07
327         Editor support available.
328
329         Enter h or `h h' for help, or `man perldebug' for more help.
330
331         main::(-e:1):   0                       
332
333 Now build an on-the-fly object over a couple of lines (note the backslash):
334
335         DB<1> $obj = bless({'unique_id'=>'123', 'attr'=> \
336         cont:   {'col' => 'black', 'things' => [qw(this that etc)]}}, 'MY_class')
337
338 And let's have a look at it:
339  
340         DB<2> x $obj
341         0  MY_class=HASH(0x828ad98)
342                 'attr' => HASH(0x828ad68)
343         'col' => 'black'
344         'things' => ARRAY(0x828abb8)
345                 0  'this'
346                 1  'that'
347                 2  'etc'
348                 'unique_id' => 123       
349         DB<3>
350
351 Useful, huh?  You can eval nearly anything in there, and experiment with bits
352 of code or regexes until the cows come home:
353
354         DB<3> @data = qw(this that the other atheism leather theory scythe)
355         
356         DB<4> p 'saw -> '.($cnt += map { print "\t:\t$_\n" } grep(/the/, sort @data))
357         atheism
358         leather
359         other
360         scythe
361         the
362         theory  
363         saw -> 6
364
365 If you want to see all the command history, an 'H':
366
367         DB<5> H
368         4: p 'saw -> '.($cnt += map { print "\t:\t$_\n" } grep(/the/, sort @data))
369         3: @data = qw(this that the other atheism leather theory scythe)
370         2: x $obj
371         1: $obj = bless({'unique_id'=>'123', 'attr'=>
372         {'col' => 'black', 'things' => [qw(this that etc)]}}, 'MY_class')
373         DB<5>
374         
375 And if you want to repeat any previous command, use the exclamation: '!':
376
377         DB<5> !4
378         p 'saw -> '.($cnt += map { print "$_\n" } grep(/the/, sort @data))
379         atheism
380         leather
381         other
382         scythe
383         the
384         theory  
385         saw -> 12
386
387
388 =head1 Stepping through code
389
390 Here's a simple program which converts between celsius and farenheit, it too
391 has a problem:
392
393         #!/usr/bin/perl -w
394         use strict;
395
396         my $arg = $ARGV[0] || '-c20';
397
398         if ($arg =~ /^\-(c|f)((\-|\+)*\d+(\.\d+)*)$/) {
399                 my ($deg, $num) = ($1, $2);
400                 my ($in, $out) = ($num, $num);
401                 if ($deg eq 'c') {
402                         $deg = 'f';
403                         $out = &c2f($num);
404                 } else {
405                         $deg = 'c';
406                         $out = &f2c($num);
407                 }
408                 $out = sprintf('%0.2f', $out);
409                 $out =~ s/^((\-|\+)*\d+)\.0+$/$1/;
410                 print "$out $deg\n";
411         } else {
412                 print "Usage: $0 -[c|f] num\n";
413         }
414         exit;
415
416         sub f2c {
417                 my $f = shift;
418                 my $c = 5 * $f - 32 / 9;
419                 return $c;
420         }
421
422         sub c2f {
423                 my $c = shift;
424                 my $f = 9 * $c / 5 + 32;
425                 return $f;
426         }
427
428
429 For some reason, the farenheit to celsius conversion fails to return the
430 expected output.  This is what it does:
431
432         > temp -c0.72
433         33.30 f
434         
435         > temp -f33.3
436         162.94 c
437         
438 Not very consistent!  We'll set a breakpoint in the code manually and run it
439 under the debugger to see what's going on.  A breakpoint is a flag, to which
440 the debugger will run without interuption, when it reaches the breakpoint, it
441 will stop execution and offer a prompt for further interaction.  In normal
442 use, these debugger commands are completely ignored, and they are safe - if a
443 little messy, to leave in production code.
444         
445         my ($in, $out) = ($num, $num);
446         $DB::single=2; # insert at line 9!
447         if ($deg eq 'c') 
448                 ...
449         
450         > perl -d temp -f33.3
451         Default die handler restored.
452
453         Loading DB routines from perl5db.pl version 1.07
454         Editor support available.
455
456         Enter h or `h h' for help, or `man perldebug' for more help.
457
458         main::(temp:4): my $arg = $ARGV[0] || '-c100';     
459
460 We'll simply continue down to our pre-set breakpoint with a 'c':
461
462         DB<1> c
463         main::(temp:10):                if ($deg eq 'c') {   
464
465 Followed by a window command to see where we are:
466         
467         DB<2> w
468         7:              my ($deg, $num) = ($1, $2);
469         8:              my ($in, $out) = ($num, $num);
470         9:              $DB::single=2;
471         10==>           if ($deg eq 'c') {
472         11:                     $deg = 'f';
473         12:                     $out = &c2f($num);
474         13              } else {
475         14:                     $deg = 'c';
476         15:                     $out = &f2c($num);
477         16              }                             
478
479 And a print to show what values we're currently using:
480
481         DB<3> p $deg, $num
482         f33.3
483                 
484 We can put another break point on any line beginning with a colon, we'll use
485 line 17 as that's just as we come out of the subroutine, and we'd like to
486 pause there later on:
487         
488         DB<4> b 17
489         
490 There's no feedback from this, but you can see what breakpoints are set by
491 using the list 'L' command:
492
493         DB<5> L
494         temp:
495                 17:            print "$out $deg\n";
496                 break if (1)     
497
498 Note that to delete a breakpoint you use 'd' or 'D'.
499
500 Now we'll continue down into our subroutine, this time rather than by line
501 number, we'll use the subroutine name, followed by the now familiar 'w':
502
503         DB<6> c f2c
504         main::f2c(temp:30):             my $f = shift;  
505
506         DB<7> w
507         27      }
508         28
509         29      sub f2c {
510         30==>           my $f = shift;
511         31:             my $c = 5 * $f - 32 / 9;
512         32:             return $c;
513         33      }
514         34           
515
516
517 Note that if there was a subroutine call between us and line 32, and we didn't
518 want to single-step through it, we could use the next command 'n', which would
519 execute the sub, but not descend into it for inspection.  In this case though,
520 we simply single step down to line 32:
521
522         DB<8> s 32 
523         main::f2c(temp:28):             return $c; 
524         
525 And have a look at the return value:
526
527         DB<9> p $c
528         162.944444444444
529
530 This is not the right answer at all, but the sum looks correct.  I wonder if
531 it's anything to do with operator precedence?  We'll try a couple of other
532 possibilities with our sum:
533
534         DB<10> p (5 * $f - 32 / 9)
535         162.944444444444
536         
537         DB<11> p 5 * $f - (32 / 9) 
538         162.944444444444
539         
540         DB<12> p (5 * $f) - 32 / 9
541         162.944444444444
542         
543         DB<13> p 5 * ($f - 32) / 9
544         0.722222222222221
545
546 :-) that's more like it!  Ok, now we can set our return variable and we'll
547 return out of the sub with an 'r':
548
549         DB<14> $c = 5 * ($f - 32) / 9
550         
551         DB<15> r
552         scalar context return from main::f2c: 0.722222222222221
553         
554 Looks good, let's just continue off the end of the script:
555
556         DB<16> c
557         0.72 c 
558         Debugged program terminated.  Use q to quit or R to restart,
559         use O inhibit_exit to avoid stopping after program termination,
560         h q, h R or h O to get additional info.   
561
562 A quick fix to the offending line (insert the missing parentheses) in the
563 actual program and we're finished.
564
565
566 =head1 Placeholder for a, w, t, T
567
568 Actions, watch variables, stack traces on the TODO list.
569
570         a 
571         
572         W 
573         
574         t 
575         
576         T
577
578
579 =head1 Regular expressions
580
581 Ever wanted to know what a regex looked like?  You'll need perl compiled with
582 the DEBUGGING flag for this one:
583         
584         > perl -Dr -e '/^pe(a)*rl$/i'
585         Compiling REx `^pe(a)*rl$'
586         size 17 first at 2
587         rarest char
588          at 0
589            1: BOL(2)
590            2: EXACTF <pe>(4)
591            4: CURLYN[1] {0,32767}(14)
592            6:   NOTHING(8)
593            8:   EXACTF <a>(0)
594           12:   WHILEM(0)
595           13: NOTHING(14)
596           14: EXACTF <rl>(16)
597           16: EOL(17)
598           17: END(0)
599         floating `'$ at 4..2147483647 (checking floating) stclass `EXACTF <pe>'
600 anchored(BOL) minlen 4
601         Omitting $` $& $' support.
602          
603         EXECUTING...
604
605         Freeing REx: `^pe(a)*rl$'  
606
607 Did you really want to know? :-)
608
609
610 =head1 Some ideas for output
611
612 To get all the output from your error log, and not miss any messages via
613 helpful operating system buffering, insert a line like this, at the start of
614 your script:
615
616         $|=1;   
617
618 To watch the tail of a dynamically growing logfile, (from the command line):
619
620         tail -f $error_log
621
622 Wrapping all die calls in a handler routine can be useful to see how, and from
623 where, they're being called, L<perlvar> has more information:
624
625         BEGIN { $SIG{__DIE__} = sub { use Carp; Carp::confess(@_) } }
626
627 Various useful techniques for the redirection of STDOUT and STDERR filehandles
628 are explained in L<perlfunc> and L<perlopentut> and L<perlfaq8>
629
630
631 =head1 CGI
632
633 Just a hint here for all those CGI programmers who can't figure out how on
634 earth to get past that 'waiting for input' prompt, try something like this:
635
636         > perl -d my_cgi.pl -nodebug 
637
638 Of course 'L<perldoc CGI>' and L<perlfaq9> will tell you more.
639
640
641 =head1 GUIs
642
643 The command line interface is tightly integrated with an B<emacs> extension
644 and there's a B<vi> interface too.  
645
646 You don't have to do this all on the command line, though, there are a few GUI
647 options out there.  The nice thing about these is you can wave a mouse over a
648 variable and a dump of it's data will appear in an appropriate window, or in a
649 popup balloon, no more tiresome typing of 'x $varname' :-)
650
651 In particular have a hunt around for the following:
652
653 B<ptkdb> perlTK based wrapper for the built-in debugger
654
655 B<ddd> data display debugger
656         
657 B<PerlDevKit> and B<PerlBuilder> are NT specific
658
659 NB. (more info on these and others would be appreciated).
660
661
662 =head1 Summary
663
664 We've seen how to encourage good coding practices with B<use strict> and
665 B<-w>.  We can run the perl debugger B<perl -d scriptname> to inspect your
666 data from within the perl debugger with the B<p> and B<x> commands.  You can
667 walk through your code, set breakpoints with B<b> and step through that code
668 with B<s> or B<n>, continue with B<c> and return from a sub with B<r>.  Fairly
669 intuitive stuff when you get down to it.  
670
671 There is of course lots more to find out about, this has just scratched the
672 surface.  The best way to learn more is to use perldoc to find out more about
673 the language, to read the on-line help (L<perldebug> is probably the next
674 place to go), and of course, experiment.  
675
676
677 =head1 SEE ALSO
678
679 L<perldebug>, 
680 L<perldebguts>, 
681 L<perldiag>,
682 L<dprofpp>,
683 L<perlrun>
684
685
686 =head1 AUTHOR
687
688 Richard Foley <richard@rfi.net> Copyright (c) 2000
689
690
691 =head1 CONTRIBUTORS
692
693 Various people have made helpful suggestions and contributions, in particular:
694
695 Ronald J Kimball <rjk@linguist.dartmouth.edu>
696
697 Hugo <hv@crypt.compulink.co.uk>
698