Home
Main website
Display Sidebar
Hide Ads
Recent Changes
View Source:
perldebtut(1)
Edit
PageHistory
Diff
Info
LikePages
PERLDEBTUT !!!PERLDEBTUT NAME DESCRIPTION use strict Looking at data and -w and w help Stepping through code Placeholder for a, w, t, T REGULAR EXPRESSIONS OUTPUT TIPS CGI GUIs SUMMARY SEE ALSO AUTHOR CONTRIBUTORS ---- !!NAME perldebtut - Perl debugging tutorial !!DESCRIPTION A (very) lightweight introduction in the use of the perl debugger, and a pointer to existing, deeper sources of information on the subject of debugging perl programs. There's an extraordinary number of people out there who don't appear to know anything about using the perl debugger, though they use the language every day. This is for them. !!use strict First of all, there's a few things you can do to make your life a lot more straightforward when it comes to debugging perl programs, without using the debugger at all. To demonstrate, here's a simple script with a problem: #!/usr/bin/perl $var1 = 'Hello World'; # always wanted to do that :-) $var2 = print $var2; exit; While this compiles and runs happily, it probably won't do what's expected, namely it doesn't print ``Hello Worldn'' at all; It will on the other hand do exactly what it was told to do, computers being a bit that way inclined. That is, it will print out a newline character, and you'll get what looks like a blank line. It looks like there's 2 variables when (because of the typo) there's really 3: $var1 = 'Hello World' $varl = undef $var2 = To catch this kind of problem, we can force each variable to be declared before use by pulling in the strict module, by putting 'use strict;' after the first line of the script. Now when you run it, perl complains about the 3 undeclared variables and we get four error messages because one variable is referenced twice: Global symbol Luvverly! and to fix this we declare all variables explicitly and now our script looks like this: #!/usr/bin/perl use strict; my $var1 = 'Hello World'; my $varl = ''; my $var2 = print $var2; exit; We then do (always a good idea) a syntax check before we try to run it again: And now when we run it, we get ``n'' still, but at least we know why. Just getting this script to compile has exposed the '$varl' (with the letter 'l) variable, and simply changing $varl to $var1 solves the problem. !!Looking at data and -w and w Ok, but how about when you want to really see your data, what's in that dynamic variable, just before using it? #!/usr/bin/perl use strict; my $key = 'welcome'; my %data = ( 'this' = print Looks OK , after it's been through the syntax check (perl -c scriptname), we run it and all we get is a blank line again! Hmmmm. One common debugging approach here, would be to liberally sprinkle a few print statements, to add a check just before we print out our data, and another just after: print And try again: done: '' After much staring at the same piece of code and not seeing the wood for the trees for some time, we get a cup of coffee and try another approach. That is, we bring in the cavalry by giving perl the '__-d__' switch on the command line: Loading DB routines from perl5db.pl version 1.07 Editor support available. Enter h or `h h' for help, or `man perldebug' for more help. main::(./data:4): my $key = 'welcome'; Now, what we've done here is to launch the built-in perl debugger on our script. It's stopped at the first line of executable code and is waiting for input. Before we go any further, you'll want to know how to quit the debugger: use just the letter '__q__', not the words 'quit' or 'exit': DB That's it, you're back on home turf again. !!help Fire the debugger up again on your script and we'll look at the help menu. There's a couple of ways of calling help: a simple '__h__' will get you a long scrolled list of help, '__h__' (pipe-h) will pipe the help through your pager ('more' or 'less' probably), and finally, '__h h__' (h-space-h) will give you a helpful mini-screen snapshot: DB More confusing options than you can shake a big stick at! It's not as bad as it looks and it's very useful to know more about all of it, and fun too! There's a couple of useful ones to know about straight away. You wouldn't think we're using any libraries at all at the moment, but '__v__' will show which modules are currently loaded, by the debugger as well your script. '__V__' and '__X__' show variables in the program by package scope and can be constrained by pattern. '__m__' shows methods and '__S__' shows all subroutines (by pattern): DB Using 'X' and cousins requires you not to use the type identifiers ($@%), just the 'name': DM Remember we're in our tiny program with a problem, we should have a look at where we are, and what our data looks like. First of all let's have a window on our present position (the first line of code in this case), via the letter '__w__': DB At line number 4 is a helpful pointer, that tells you where you are now. To see more code, type 'w' again: DB And if you wanted to list line 5 again, type 'l 5', (note the space): DB In this case, there's not much to see, but of course normally there's pages of stuff to wade through, and 'l' can be very useful. To reset your view to the line we're about to execute, type a lone period '.': DB The line shown is the one that is about to be executed __next__, it hasn't happened yet. So while we can print a variable with the letter '__p__', at this point all we'd get is an empty (undefined) value back. What we need to do is to step through the next executable statement with an '__s__': DB Now we can have a look at that first ($key) variable: DB line 13 is where the action is, so let's continue down to there via the letter '__c__', which by the way, inserts a 'one-time-only' breakpoint at the given line or sub routine: DB We've gone past our check (where 'All OK ' was printed) and have stopped just before the meat of our task. We could try to print out a couple of variables to see what is happening: DB Not much in there, lets have a look at our hash: DB DB Well, this isn't very easy to read, and using the helpful manual (__h h__), the '__x__' command looks promising: DB That's not much help, a couple of welcomes in there, but no indication of which are keys, and which are values, it's just a listed array dump and, in this case, not particularly helpful. The trick here, is to use a __reference__ to the data structure: DB The reference is truly dumped and we can finally see what we're dealing with. Our quoting was perfectly valid but wrong for our purposes, with 'and jerry' being treated as 2 separate words rather than a phrase, thus throwing the evenly paired hash structure out of alignment. The '__-w__' switch would have told us about this, had we used it at the start, and saved us a lot of trouble: We fix our quoting: 'tom' = While we're here, take a closer look at the '__x__' command, it's really useful and will merrily dump out nested references, complete objects, partial objects - just about whatever you throw at it: Let's make a quick object and x-plode it, first we'll start the the debugger: it wants some form of input from STDIN , so we give it something non-commital, a zero: Loading DB routines from perl5db.pl version 1.07 Editor support available. Enter h or `h h' for help, or `man perldebug' for more help. main::(-e:1): 0 Now build an on-the-fly object over a couple of lines (note the backslash): DB And let's have a look at it: DB Useful, huh? You can eval nearly anything in there, and experiment with bits of code or regexes until the cows come home: DB DB If you want to see the command History, type an '__H__': DB And if you want to repeat any previous command, use the exclamation: '__!__': DB For more on references see perlref and perlreftut !!Stepping through code Here's a simple program which converts between Celsius and Fahrenheit, it too has a problem: #!/usr/bin/perl -w use strict; my $arg = $ARGV[[0] '-c20'; if ($arg =~ /^-(cf)((-+)*d+(.d+)*)$/) { my ($deg, $num) = ($1, $2); my ($in, $out) = ($num, $num); if ($deg eq 'c') { $deg = 'f'; $out = sub f2c { my $f = shift; my $c = 5 * $f - 32 / 9; return $c; } sub c2f { my $c = shift; my $f = 9 * $c / 5 + 32; return $f; } For some reason, the Fahrenheit to Celsius conversion fails to return the expected output. This is what it does: Not very consistent! We'll set a breakpoint in the code manually and run it under the debugger to see what's going on. A breakpoint is a flag, to which the debugger will run without interruption, when it reaches the breakpoint, it will stop execution and offer a prompt for further interaction. In normal use, these debugger commands are completely ignored, and they are safe - if a little messy, to leave in production code. my ($in, $out) = ($num, $num); $DB::single=2; # insert at line 9! if ($deg eq 'c') ... Loading DB routines from perl5db.pl version 1.07 Editor support available. Enter h or `h h' for help, or `man perldebug' for more help. main::(temp:4): my $arg = $ARGV[[0] '-c100'; We'll simply continue down to our pre-set breakpoint with a '__c__': DB Followed by a window command to see where we are: DB And a print to show what values we're currently using: DB We can put another break point on any line beginning with a colon, we'll use line 17 as that's just as we come out of the subroutine, and we'd like to pause there later on: DB There's no feedback from this, but you can see what breakpoints are set by using the list 'L' command: DB Note that to delete a breakpoint you use 'd' or 'D'. Now we'll continue down into our subroutine, this time rather than by line number, we'll use the subroutine name, followed by the now familiar 'w': DB DB Note that if there was a subroutine call between us and line 29, and we wanted to __single-step__ through it, we could use the '__s__' command, and to step over it we would use '__n__' which would execute the sub, but not descend into it for inspection. In this case though, we simply continue down to line 29: DB And have a look at the return value: DB This is not the right answer at all, but the sum looks correct. I wonder if it's anything to do with operator precedence? We'll try a couple of other possibilities with our sum: DB DB DB DB :-) that's more like it! Ok, now we can set our return variable and we'll return out of the sub with an 'r': DB DB Looks good, let's just continue off the end of the script: DB A quick fix to the offending line (insert the missing parentheses) in the actual program and we're finished. !!Placeholder for a, w, t, T Actions, watch variables, stack traces etc.: on the TODO list. a W t T !!REGULAR EXPRESSIONS Ever wanted to know what a regex looked like? You'll need perl compiled with the DEBUGGING flag for this one: EXECUTING... Freeing REx: `^pe(a)*rl$' Did you really want to know? :-) For more gory details on getting regular expressions to work, have a look at perlre, perlretut, and to decode the mysterious labels ( BOL and CURLYN , etc. above), see perldebguts. !!OUTPUT TIPS To get all the output from your error log, and not miss any messages via helpful operating system buffering, insert a line like this, at the start of your script: $=1; To watch the tail of a dynamically growing logfile, (from the command line): tail -f $error_log Wrapping all die calls in a handler routine can be useful to see how, and from where, they're being called, perlvar has more information: BEGIN { $SIG{__DIE__} = sub { require Carp; Carp::confess(@_) } } Various useful techniques for the redirection of STDOUT and STDERR filehandles are explained in perlopentut and perlfaq8. !!CGI Just a quick hint here for all those CGI programmers who can't figure out how on earth to get past that 'waiting for input' prompt, when running their CGI script from the command-line, try something like this: Of course CGI and perlfaq9 will tell you more. !!GUIs The command line interface is tightly integrated with an __emacs__ extension and there's a __vi__ interface too. You don't have to do this all on the command line, though, there are a few GUI options out there. The nice thing about these is you can wave a mouse over a variable and a dump of it's data will appear in an appropriate window, or in a popup balloon, no more tiresome typing of 'x $varname' :-) In particular have a hunt around for the following: __ptkdb__ perlTK based wrapper for the built-in debugger __ddd__ data display debugger __!PerlDevKit__ and __!PerlBuilder__ are NT specific NB . (more info on these and others would be appreciated). !!SUMMARY We've seen how to encourage good coding practices with __use strict__ and __-w__. We can run the perl debugger __perl -d scriptname__ to inspect your data from within the perl debugger with the __p__ and __x__ commands. You can walk through your code, set breakpoints with __b__ and step through that code with __s__ or __n__, continue with __c__ and return from a sub with __r__. Fairly intuitive stuff when you get down to it. There is of course lots more to find out about, this has just scratched the surface. The best way to learn more is to use perldoc to find out more about the language, to read the on-line help (perldebug is probably the next place to go), and of course, experiment. !!SEE ALSO perldebug, perldebguts, perldiag, dprofpp, perlrun !!AUTHOR Richard Foley !!CONTRIBUTORS Various people have made helpful suggestions and contributions, in particular: Ronald J Kimball Hugo van der Sanden Peter Scott ----
One page links to
perldebtut(1)
:
Man1p
This page is a man page (or other imported legacy content). We are unable to automatically determine the license status of this page.