1PERLDEBTUT(1) Perl Programmers Reference Guide PERLDEBTUT(1)
2
3
4
6 perldebtut - Perl debugging tutorial
7
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 lan‐
15 guage every day. This is for them.
16
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 vari‐
36 ables 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
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 script‐
100 name), 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
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 [in expr]
157 v [line] View around line n [expr] Next, steps over subs
158 f filename View source in file <CR/Enter> Repeat last n or s
159 /pattern/ ?patt? Search forw/backw r Return from subroutine
160 M Show module versions c [ln⎪sub] Continue until position
161 Debugger controls: L List break/watch/actions
162 o [...] Set debugger options t [expr] Toggle trace [trace expr]
163 <[<]⎪{[{]⎪>[>] [cmd] Do pre/post-prompt b [ln⎪event⎪sub] [cnd] Set breakpoint
164 ! [N⎪pat] Redo a previous command B ln⎪* Delete a/all breakpoints
165 H [-num] Display last num commands a [ln] cmd Do cmd before line
166 = [a val] Define/list an alias A ln⎪* Delete a/all actions
167 h [db_cmd] Get help on command w expr Add a watch expression
168 h h Complete help page W expr⎪* Delete a/all watch exprs
169 ⎪[⎪]db_cmd Send output to pager ![!] syscmd Run cmd in a subprocess
170 q or ^D Quit R Attempt a restart
171 Data Examination: expr Execute perl code, also see: s,n,t expr
172 x⎪m expr Evals expr in list context, dumps the result or lists methods.
173 p expr Print expression (uses script's current package).
174 S [[!]pat] List subroutine names [not] matching pattern
175 V [Pk [Vars]] List Variables in Package. Vars can be ~pattern or !pattern.
176 X [Vars] Same as "V current_package [Vars]".
177 y [n [Vars]] List lexicals in higher scope <n>. Vars same as V.
178 For more help, type h cmd_letter, or run man perldebug for all docs.
179
180 More confusing options than you can shake a big stick at! It's not as
181 bad as it looks and it's very useful to know more about all of it, and
182 fun too!
183
184 There's a couple of useful ones to know about straight away. You
185 wouldn't think we're using any libraries at all at the moment, but 'M'
186 will show which modules are currently loaded, and their version number,
187 while 'm' will show the methods, and 'S' shows all subroutines (by pat‐
188 tern) as shown below. 'V' and 'X' show variables in the program by
189 package scope and can be constrained by pattern.
190
191 DB<2>S str
192 dumpvar::stringify
193 strict::bits
194 strict::import
195 strict::unimport
196
197 Using 'X' and cousins requires you not to use the type identifiers
198 ($@%), just the 'name':
199
200 DM<3>X ~err
201 FileHandle(stderr) => fileno(2)
202
203 Remember we're in our tiny program with a problem, we should have a
204 look at where we are, and what our data looks like. First of all let's
205 view some code at our present position (the first line of code in this
206 case), via 'v':
207
208 DB<4> v
209 1 #!/usr/bin/perl
210 2: use strict;
211 3
212 4==> my $key = 'welcome';
213 5: my %data = (
214 6 'this' => qw(that),
215 7 'tom' => qw(and jerry),
216 8 'welcome' => q(Hello World),
217 9 'zip' => q(welcome),
218 10 );
219
220 At line number 4 is a helpful pointer, that tells you where you are
221 now. To see more code, type 'v' again:
222
223 DB<4> v
224 8 'welcome' => q(Hello World),
225 9 'zip' => q(welcome),
226 10 );
227 11: my @data = keys %data;
228 12: print "All OK\n" if grep($key, keys %data);
229 13: print "$data{$key}\n";
230 14: print "done: '$data{$key}'\n";
231 15: exit;
232
233 And if you wanted to list line 5 again, type 'l 5', (note the space):
234
235 DB<4> l 5
236 5: my %data = (
237
238 In this case, there's not much to see, but of course normally there's
239 pages of stuff to wade through, and 'l' can be very useful. To reset
240 your view to the line we're about to execute, type a lone period '.':
241
242 DB<5> .
243 main::(./data_a:4): my $key = 'welcome';
244
245 The line shown is the one that is about to be executed next, it hasn't
246 happened yet. So while we can print a variable with the letter 'p', at
247 this point all we'd get is an empty (undefined) value back. What we
248 need to do is to step through the next executable statement with an
249 's':
250
251 DB<6> s
252 main::(./data_a:5): my %data = (
253 main::(./data_a:6): 'this' => qw(that),
254 main::(./data_a:7): 'tom' => qw(and jerry),
255 main::(./data_a:8): 'welcome' => q(Hello World),
256 main::(./data_a:9): 'zip' => q(welcome),
257 main::(./data_a:10): );
258
259 Now we can have a look at that first ($key) variable:
260
261 DB<7> p $key
262 welcome
263
264 line 13 is where the action is, so let's continue down to there via the
265 letter 'c', which by the way, inserts a 'one-time-only' breakpoint at
266 the given line or sub routine:
267
268 DB<8> c 13
269 All OK
270 main::(./data_a:13): print "$data{$key}\n";
271
272 We've gone past our check (where 'All OK' was printed) and have stopped
273 just before the meat of our task. We could try to print out a couple
274 of variables to see what is happening:
275
276 DB<9> p $data{$key}
277
278 Not much in there, lets have a look at our hash:
279
280 DB<10> p %data
281 Hello Worldziptomandwelcomejerrywelcomethisthat
282
283 DB<11> p keys %data
284 Hello Worldtomwelcomejerrythis
285
286 Well, this isn't very easy to read, and using the helpful manual (h h),
287 the 'x' command looks promising:
288
289 DB<12> x %data
290 0 'Hello World'
291 1 'zip'
292 2 'tom'
293 3 'and'
294 4 'welcome'
295 5 undef
296 6 'jerry'
297 7 'welcome'
298 8 'this'
299 9 'that'
300
301 That's not much help, a couple of welcomes in there, but no indication
302 of which are keys, and which are values, it's just a listed array dump
303 and, in this case, not particularly helpful. The trick here, is to use
304 a reference to the data structure:
305
306 DB<13> x \%data
307 0 HASH(0x8194bc4)
308 'Hello World' => 'zip'
309 'jerry' => 'welcome'
310 'this' => 'that'
311 'tom' => 'and'
312 'welcome' => undef
313
314 The reference is truly dumped and we can finally see what we're dealing
315 with. Our quoting was perfectly valid but wrong for our purposes, with
316 'and jerry' being treated as 2 separate words rather than a phrase,
317 thus throwing the evenly paired hash structure out of alignment.
318
319 The '-w' switch would have told us about this, had we used it at the
320 start, and saved us a lot of trouble:
321
322 > perl -w data
323 Odd number of elements in hash assignment at ./data line 5.
324
325 We fix our quoting: 'tom' => q(and jerry), and run it again, this time
326 we get our expected output:
327
328 > perl -w data
329 Hello World
330
331 While we're here, take a closer look at the 'x' command, it's really
332 useful and will merrily dump out nested references, complete objects,
333 partial objects - just about whatever you throw at it:
334
335 Let's make a quick object and x-plode it, first we'll start the debug‐
336 ger: it wants some form of input from STDIN, so we give it something
337 non-committal, a zero:
338
339 > perl -de 0
340 Default die handler restored.
341
342 Loading DB routines from perl5db.pl version 1.07
343 Editor support available.
344
345 Enter h or `h h' for help, or `man perldebug' for more help.
346
347 main::(-e:1): 0
348
349 Now build an on-the-fly object over a couple of lines (note the back‐
350 slash):
351
352 DB<1> $obj = bless({'unique_id'=>'123', 'attr'=> \
353 cont: {'col' => 'black', 'things' => [qw(this that etc)]}}, 'MY_class')
354
355 And let's have a look at it:
356
357 DB<2> x $obj
358 0 MY_class=HASH(0x828ad98)
359 'attr' => HASH(0x828ad68)
360 'col' => 'black'
361 'things' => ARRAY(0x828abb8)
362 0 'this'
363 1 'that'
364 2 'etc'
365 'unique_id' => 123
366 DB<3>
367
368 Useful, huh? You can eval nearly anything in there, and experiment
369 with bits of code or regexes until the cows come home:
370
371 DB<3> @data = qw(this that the other atheism leather theory scythe)
372
373 DB<4> p 'saw -> '.($cnt += map { print "\t:\t$_\n" } grep(/the/, sort @data))
374 atheism
375 leather
376 other
377 scythe
378 the
379 theory
380 saw -> 6
381
382 If you want to see the command History, type an 'H':
383
384 DB<5> H
385 4: p 'saw -> '.($cnt += map { print "\t:\t$_\n" } grep(/the/, sort @data))
386 3: @data = qw(this that the other atheism leather theory scythe)
387 2: x $obj
388 1: $obj = bless({'unique_id'=>'123', 'attr'=>
389 {'col' => 'black', 'things' => [qw(this that etc)]}}, 'MY_class')
390 DB<5>
391
392 And if you want to repeat any previous command, use the exclamation:
393 '!':
394
395 DB<5> !4
396 p 'saw -> '.($cnt += map { print "$_\n" } grep(/the/, sort @data))
397 atheism
398 leather
399 other
400 scythe
401 the
402 theory
403 saw -> 12
404
405 For more on references see perlref and perlreftut
406
408 Here's a simple program which converts between Celsius and Fahrenheit,
409 it too has a problem:
410
411 #!/usr/bin/perl -w
412 use strict;
413
414 my $arg = $ARGV[0] ⎪⎪ '-c20';
415
416 if ($arg =~ /^\-(c⎪f)((\-⎪\+)*\d+(\.\d+)*)$/) {
417 my ($deg, $num) = ($1, $2);
418 my ($in, $out) = ($num, $num);
419 if ($deg eq 'c') {
420 $deg = 'f';
421 $out = &c2f($num);
422 } else {
423 $deg = 'c';
424 $out = &f2c($num);
425 }
426 $out = sprintf('%0.2f', $out);
427 $out =~ s/^((\-⎪\+)*\d+)\.0+$/$1/;
428 print "$out $deg\n";
429 } else {
430 print "Usage: $0 -[c⎪f] num\n";
431 }
432 exit;
433
434 sub f2c {
435 my $f = shift;
436 my $c = 5 * $f - 32 / 9;
437 return $c;
438 }
439
440 sub c2f {
441 my $c = shift;
442 my $f = 9 * $c / 5 + 32;
443 return $f;
444 }
445
446 For some reason, the Fahrenheit to Celsius conversion fails to return
447 the expected output. This is what it does:
448
449 > temp -c0.72
450 33.30 f
451
452 > temp -f33.3
453 162.94 c
454
455 Not very consistent! We'll set a breakpoint in the code manually and
456 run it under the debugger to see what's going on. A breakpoint is a
457 flag, to which the debugger will run without interruption, when it
458 reaches the breakpoint, it will stop execution and offer a prompt for
459 further interaction. In normal use, these debugger commands are com‐
460 pletely ignored, and they are safe - if a little messy, to leave in
461 production code.
462
463 my ($in, $out) = ($num, $num);
464 $DB::single=2; # insert at line 9!
465 if ($deg eq 'c')
466 ...
467
468 > perl -d temp -f33.3
469 Default die handler restored.
470
471 Loading DB routines from perl5db.pl version 1.07
472 Editor support available.
473
474 Enter h or `h h' for help, or `man perldebug' for more help.
475
476 main::(temp:4): my $arg = $ARGV[0] ⎪⎪ '-c100';
477
478 We'll simply continue down to our pre-set breakpoint with a 'c':
479
480 DB<1> c
481 main::(temp:10): if ($deg eq 'c') {
482
483 Followed by a view command to see where we are:
484
485 DB<1> v
486 7: my ($deg, $num) = ($1, $2);
487 8: my ($in, $out) = ($num, $num);
488 9: $DB::single=2;
489 10==> if ($deg eq 'c') {
490 11: $deg = 'f';
491 12: $out = &c2f($num);
492 13 } else {
493 14: $deg = 'c';
494 15: $out = &f2c($num);
495 16 }
496
497 And a print to show what values we're currently using:
498
499 DB<1> p $deg, $num
500 f33.3
501
502 We can put another break point on any line beginning with a colon,
503 we'll use line 17 as that's just as we come out of the subroutine, and
504 we'd like to pause there later on:
505
506 DB<2> b 17
507
508 There's no feedback from this, but you can see what breakpoints are set
509 by using the list 'L' command:
510
511 DB<3> L
512 temp:
513 17: print "$out $deg\n";
514 break if (1)
515
516 Note that to delete a breakpoint you use 'd' or 'D'.
517
518 Now we'll continue down into our subroutine, this time rather than by
519 line number, we'll use the subroutine name, followed by the now famil‐
520 iar 'v':
521
522 DB<3> c f2c
523 main::f2c(temp:30): my $f = shift;
524
525 DB<4> v
526 24: exit;
527 25
528 26 sub f2c {
529 27==> my $f = shift;
530 28: my $c = 5 * $f - 32 / 9;
531 29: return $c;
532 30 }
533 31
534 32 sub c2f {
535 33: my $c = shift;
536
537 Note that if there was a subroutine call between us and line 29, and we
538 wanted to single-step through it, we could use the 's' command, and to
539 step over it we would use 'n' which would execute the sub, but not
540 descend into it for inspection. In this case though, we simply con‐
541 tinue down to line 29:
542
543 DB<4> c 29
544 main::f2c(temp:29): return $c;
545
546 And have a look at the return value:
547
548 DB<5> p $c
549 162.944444444444
550
551 This is not the right answer at all, but the sum looks correct. I won‐
552 der if it's anything to do with operator precedence? We'll try a cou‐
553 ple of other possibilities with our sum:
554
555 DB<6> p (5 * $f - 32 / 9)
556 162.944444444444
557
558 DB<7> p 5 * $f - (32 / 9)
559 162.944444444444
560
561 DB<8> p (5 * $f) - 32 / 9
562 162.944444444444
563
564 DB<9> p 5 * ($f - 32) / 9
565 0.722222222222221
566
567 :-) that's more like it! Ok, now we can set our return variable and
568 we'll return out of the sub with an 'r':
569
570 DB<10> $c = 5 * ($f - 32) / 9
571
572 DB<11> r
573 scalar context return from main::f2c: 0.722222222222221
574
575 Looks good, let's just continue off the end of the script:
576
577 DB<12> c
578 0.72 c
579 Debugged program terminated. Use q to quit or R to restart,
580 use O inhibit_exit to avoid stopping after program termination,
581 h q, h R or h O to get additional info.
582
583 A quick fix to the offending line (insert the missing parentheses) in
584 the actual program and we're finished.
585
587 Actions, watch variables, stack traces etc.: on the TODO list.
588
589 a
590
591 w
592
593 t
594
595 T
596
598 Ever wanted to know what a regex looked like? You'll need perl com‐
599 piled with the DEBUGGING flag for this one:
600
601 > perl -Dr -e '/^pe(a)*rl$/i'
602 Compiling REx `^pe(a)*rl$'
603 size 17 first at 2
604 rarest char
605 at 0
606 1: BOL(2)
607 2: EXACTF <pe>(4)
608 4: CURLYN[1] {0,32767}(14)
609 6: NOTHING(8)
610 8: EXACTF <a>(0)
611 12: WHILEM(0)
612 13: NOTHING(14)
613 14: EXACTF <rl>(16)
614 16: EOL(17)
615 17: END(0)
616 floating `'$ at 4..2147483647 (checking floating) stclass `EXACTF <pe>'
617 anchored(BOL) minlen 4
618 Omitting $` $& $' support.
619
620 EXECUTING...
621
622 Freeing REx: `^pe(a)*rl$'
623
624 Did you really want to know? :-) For more gory details on getting regu‐
625 lar expressions to work, have a look at perlre, perlretut, and to
626 decode the mysterious labels (BOL and CURLYN, etc. above), see perlde‐
627 bguts.
628
630 To get all the output from your error log, and not miss any messages
631 via helpful operating system buffering, insert a line like this, at the
632 start of your script:
633
634 $⎪=1;
635
636 To watch the tail of a dynamically growing logfile, (from the command
637 line):
638
639 tail -f $error_log
640
641 Wrapping all die calls in a handler routine can be useful to see how,
642 and from where, they're being called, perlvar has more information:
643
644 BEGIN { $SIG{__DIE__} = sub { require Carp; Carp::confess(@_) } }
645
646 Various useful techniques for the redirection of STDOUT and STDERR
647 filehandles are explained in perlopentut and perlfaq8.
648
650 Just a quick hint here for all those CGI programmers who can't figure
651 out how on earth to get past that 'waiting for input' prompt, when run‐
652 ning their CGI script from the command-line, try something like this:
653
654 > perl -d my_cgi.pl -nodebug
655
656 Of course CGI and perlfaq9 will tell you more.
657
659 The command line interface is tightly integrated with an emacs exten‐
660 sion and there's a vi interface too.
661
662 You don't have to do this all on the command line, though, there are a
663 few GUI options out there. The nice thing about these is you can wave
664 a mouse over a variable and a dump of its data will appear in an appro‐
665 priate window, or in a popup balloon, no more tiresome typing of 'x
666 $varname' :-)
667
668 In particular have a hunt around for the following:
669
670 ptkdb perlTK based wrapper for the built-in debugger
671
672 ddd data display debugger
673
674 PerlDevKit and PerlBuilder are NT specific
675
676 NB. (more info on these and others would be appreciated).
677
679 We've seen how to encourage good coding practices with use strict and
680 -w. We can run the perl debugger perl -d scriptname to inspect your
681 data from within the perl debugger with the p and x commands. You can
682 walk through your code, set breakpoints with b and step through that
683 code with s or n, continue with c and return from a sub with r. Fairly
684 intuitive stuff when you get down to it.
685
686 There is of course lots more to find out about, this has just scratched
687 the surface. The best way to learn more is to use perldoc to find out
688 more about the language, to read the on-line help (perldebug is proba‐
689 bly the next place to go), and of course, experiment.
690
692 perldebug, perldebguts, perldiag, dprofpp, perlrun
693
695 Richard Foley <richard@rfi.net> Copyright (c) 2000
696
698 Various people have made helpful suggestions and contributions, in par‐
699 ticular:
700
701 Ronald J Kimball <rjk@linguist.dartmouth.edu>
702
703 Hugo van der Sanden <hv@crypt0.demon.co.uk>
704
705 Peter Scott <Peter@PSDT.com>
706
707
708
709perl v5.8.8 2006-01-07 PERLDEBTUT(1)