Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

721 lines
21 KiB

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