Become a fan of Slashdot on Facebook


Forgot your password?
Perl Books Media Programming Book Reviews

Pro Perl Debugging 164

Michael J. Ross writes "The typical computer program has more bugs than there are ants at a picnic -- except ants are usually easier to find. Programs written in Perl are no exception, because the compactness of the language does not make any existent bugs easier to spot; they can simply be packed into fewer lines of code. To help remedy this problem, Richard Foley and Andy Lester, two seasoned Perl programmers, offer a new book, Pro Perl Debugging: From Professional to Expert." Read the rest of Michael's review.
Pro Perl Debugging: From Professional to Expert
author Richard Foley with Andy Lester
pages 269
publisher Apress
rating 8
reviewer Michael J. Ross
ISBN 1590594541
summary A comprehensive tutorial and reference for the Perl debugger

This title was published in hardcover in March 2005 by Apress, a relatively new member of the technical publishing world. The publisher has a Web page for the book that includes links to all of the source code in a Zip file, the table of contents in PDF format, and a form for submitting errata. The book comprises 269 pages, the majority of which are organized into 16 chapters: Introduction (not to be confused with the true Introduction immediately preceding it), Inspecting Variables and Getting Help, Controlling Program Execution, Debugging a Simple Command Line Program, Tracing Execution, Debugging Modules, Debugging Object-Oriented Perl, Using the Debugger As a Shell, Debugging a CGI Program, Perl Threads and Forked Processes, Debugging Regular Expressions, Debugger Customization, Optimization and Performance Hints and Tips, Command Line and GUI Debuggers, Comprehensive Command Reference, Book References and URLs.

For programmers who wish to learn how to fully utilize Perl's debugger, what options are open to them? A terse summary of the debugger's commands are always close by, within the debugger itself. Those Perl coders who have yet to try the built-in Perl debugger, really owe it to themselves to give it a whirl. In most cases, it is superior to embedding lots of "print" statements in your scripts, and then wading through the results. Simply include perl.exe's -d flag on the system command line, and you should be put right into the debugger, and see the debugger's "DB<1>" command prompt -- the "1" meaning that it is ready for your first command. To display the aforementioned command summary, simply enter "h", or "|h" to see the output one screen-ful at a time, which you will probably want to do unless your system window can show all of the dozens of lines at once. The command summary is best used as a quick reference, and naturally cannot be expected to serve as any sort of tutorial. Yet it has its use, and for that, it's fine.

Most Perl books devote at least some space to explaining the basics of firing up and using Perl's debugger. The (in)famous "camel book," Larry Wall's Programming Perl, has a chapter on the debugger. It covers breakpoints, running, stepping, tracing, displaying code, commands, debugger customization, debugger options, unattended execution, creating your own debugger, and performance profiling. Aside from that last topic, the chapter is mostly an expansion of the command summary mentioned earlier. It is sparse on examples, and does not cover any advanced topics, such as using the debugger in the context of forking, threads, and POE, as well as the debugger's special capabilities for regular expressions, CGI programs, and shelling out.

The advanced topics are where Pro Perl Debugging really shines in relation to the coverage that I have seen in any other book, partly because the authors have the space to thoroughly explore those topics in depth, and to provide much more meaty examples, with adequately illustrative sample code. Even for the more complex topics, the writing is clear, and the examples are worthwhile.

The authors clearly intend for the book to serve as both a comprehensive tutorial and a reference for the Perl debugger. In both respects, they succeed admirably. But the practical value of their accomplishment could be called into question by any programmer who has grown tired of the limitations of the Perl debugger, and has switched over to any Perl-capable standalone GUI debugger or integrated development environment (IDE). More specifically, watching a variable change value, while stepping through the lines of a Perl script using the debugger, requires that the programmer manually or programmatically echo that variable's value, by issuing a print command ("p") followed by the variable name, one way or another. This process quickly becomes tedious when multiple variables need to be watched, because each individual variable must be printed, one at a time. Admittedly, previously entered print statements can be recalled by using the up-arrow key, but only if the particular command has not been pushed out of the debugger's limited storage. This usually becomes even more frustrating when trying to print the values of indexed arrays, hashes, and nested arrays and other structures. There are workarounds, but none are pretty, and even the most promising techniques still seem to require excessive focusing on the debugger commands themselves, drawing attention away from the code being debugged.

As a result, some disheartened Perl coders eventually switch back to embedding "print" statements in their code. Fortunately, there is a better alternative, in the form of IDEs, which can automatically report the changing values of a large set of variables, none of which need to be typed in, owing to the drag-and-drop capabilities of most IDEs. There are many IDEs available, including freeware and open source offerings. Most if not all of them support advanced editing, syntax highlighting and verification, visual breakpoints, and other much-appreciated capabilities. Even if they were to lack all of these features, and only have the advantage of easily and dynamically displaying the current values of variables, then they would be much more pleasant to use than the built-in Perl debugger. This is especially true in the case of nested structures, which can be expanded with a mouse click within most IDEs. All of this being said, it should be noted that the authors include a chapter that briefly touches upon the most well-known Perl GUI debuggers -- but at only seven pages in length, the chosen applications get only a cursory treatment, highlighting their major features.

Nonetheless, given the intended purpose of Pro Perl Debugging, and its target audience, the book cannot be faulted for its contents nor its approach to presenting the material. Anyone looking for a detailed and competent explication of the native Perl debugger, would likely not be able to find a more thorough treatment anywhere else.

Michael J. Ross is a freelance writer, computer consultant, and the editor of's free newsletter."

You can purchase Pro Perl Debugging from Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.
This discussion has been archived. No new comments can be posted.

Pro Perl Debugging

Comments Filter:
  • ...there's something about an interpreted language which can be optimized down to nearly the size of machine code, only less readable.
    • by winkydink ( 650484 ) * <> on Monday December 12, 2005 @02:39PM (#14240228) Homepage Journal
      IMHO, that says more about the programmer than the language.
      • True, but computer languages are not just the bits you learn in the language reference. There is also a culture surrounding each computer language, because eventually much code has to be seen by another geek versed in the language. And the culture surrounding Perl is the computer language equivalent of an island of cannibals. There are some wonderful pieces of native art if you can get past that whole spear-you-and-eat-your-brains thing. Perl programmers seem to take a perverse enjoyment in making the r
    • ...optimized down to nearly the size of machine code, only less readable.

      But isn't that the point of writing your own code?
    • What? All perl code is perfectly readable! ;-)

      What do you mean by "optimized down to nearly the size of machine code" though? I'm not sure what you're talking about.
  • extant, surely?
  • by winkydink ( 650484 ) * <> on Monday December 12, 2005 @02:34PM (#14240184) Homepage Journal
    Properly placed and well-thought out, I can leave:

    print "a bunch o' stuff\n" if $Debugging;

    in my code forever and never have to go through the trouble of firing up an IDE.

    • print "a bunch o' stuff\n" if $Debugging;

      Alternatively, I convert print statements into logging facilities:

      open LOG, ">> $log_file" or die "Can't open $log_file: $!\n";
      # Magical happenings
      print LOG "And this happens here...\n" if $debug_flag;

      I can then match things up to my pseudocode and determine if I'm pushing values around the way I should. Of course it's made a a lot easier with "use strict;" and the -w switch enabled.

    • by hattmoward ( 695554 ) on Monday December 12, 2005 @03:11PM (#14240507)
      How many times is that conditional checked at runtime? They can add up. In perl, you could have it optimized away at compile time...
      sub DEBUG() { return 1; }


      DEBUG and print "value of blah:", $blah, $/;
      but... TIMTOWTDI ;)
    • by Mark_Uplanguage ( 444809 ) on Monday December 12, 2005 @04:13PM (#14241006)
      When debugging I emphasize the use of "warn" over "print". It's the same syntax, but the warn statements don't get spooled and therefore their timing is quicker.

      This is vital when you code just plain blows up. Using "print" means that a statement which got executed before the disaster may not make it to console, thus leading you to believe that it never got executed. "warn" avoids this problem and thus leads you to the problem more accurately. It also makes it easy to globally comment out the warn statements before going releasing the code.
    • Or you could just . . .

      use Smart::Comments;
      ### Expected: "a bunch o stuff" Got: $stuff

      . . . and have debugging statements that are easier to write, can be turned off in one place, and don't waste efficiency checking a bunch of conditionals.
      see .1/lib/Smart/ []

    • While I agree, I'd like to see a GUI ide that lets you fold debug prints down to a single red pixel line or something similar. Just so you can easily keep them around but yet be able to quickly scan through a page of code without being overwhelmed by a lot of prints.
      I still think vim is the best development environment, but even gtkvim is just a fancy xterm with a toolbar and menus. Hopefully soon a better developer than I will take vims powerful commands/features and mangle it into a full blown IDE with
    • The issue of whether to use a debugger or not is a matter of speed and ease of debugging. There's few things you can't do with print statements that you can do with the debugger. [There are some: try using printf to get a backtrace of a segfault in C.] Lacing your program with print statements to check values is a time consuming, annoying, and certainly uglifies your code. Worse still, if you didn't anticipate wanting to see the value of some variable in advance, you will have to modify your program, (compi
    • Log4Perl [] You know it makes sense.

      The only real way (the perl debugger sucks beyond belief and is only there for little bittie programs, and I've tried using it to debug client/server problems) is to use the perl debugger is through emacs, and the GUD interface, but I've given that up in favour of Log4perl.
  • Perl is a very bloated scripted language, now ruby is compact, and python somewhat compact, but Perl is surely the RPG-II of the scripting language world. And yes, I've been using Perl for over 9 years, and written tcp daemons and web portals in Perl. I love/hate it.
    • I think they speak of the actual structure of some people's Perl code, and not the size and breadth of the language and/or runtime.
    • web portals ok, but what do you mean by a tcp daemon? Do you mean a TCP stack, in which case why would you use a scripting language (even though its highly optimizable) instead of C/C++? Or do you mean a TCP server? Even if it was the latter, if performance and code size is important to you, why didn't you use C/C++? Perl is great for prototyping performance-intensive apps, but if you deploy it for any serious performance-intensive tasks, you're making somewhat of a mistake. Also, I don't know how you can c
      • Presumably he means a daemon that listens for incoming connections on a TCP port, and responds according to some protocol. And perl isn't nearly as slow as many people seem to think - it takes awhile to compile a large program, which happens at every runtime, but that shouldn't be a problem for a daemon.
      • bloated means amount of typing required to do a given task, not a terse nor powerful language compared to some. C/C++ in the same boat there, for power and terseness try OCAML or ruby. Tcp daemons means various database, queuing and xml services implemented as tcp servers and clients. Limiting factor of performance wasn't perl, was backend databases and repositories and such.
    • Wrong and wrong. Perl is very compact, not only the language, but the interpreter as well. The actual interpreter is only ~1MB IIRC, and it's one of the only languages where programmers play 'Golf' and try to write a functional program in as few steps as possible. Fast, feature rich, and powerful, it's definitely not bloated.
  • by Jerry Coffin ( 824726 ) on Monday December 12, 2005 @02:40PM (#14240239)
    Hmm...let's see: the basic idea here is that the book is devoted to the (text mode) debugger built into Perl, but even the review comes barely short of flat-out stating that nearly nobody is ever likely to be happy with this, and anybody doing any real work will want to use an IDE with a GUI-style debugger instead.

    I suppose this might be handy a bit the same way knowing something like ed or vi is handy for anybody using UNIX (or similar) systems -- even the absolute strangest distribution (or installation) will almost inevitably include at least that much and it's pretty consistent. OTOH, debugging Perl on a machine that hasn't really been equipped for it doesn't sound to me like a lot better idea than using ed to write most of my code...

    • better idea than using ed to write most of my code...

      but, but, ed is the standard editor [], dammit!

    • I've been a serious Perl programmer for about eight years, and I never use an IDE. I always do my debugging at the terminal. [I do use a syntax highlighting editor.] I understand that a lot of people like IDEs, but I find them annoying and hampering. I'd prefer to have a text mode debugger pipe a large data structure to less and let me use / and ? to find various things in the pager. I haven't found an IDE yet that lets you do that easily. This is a very useful technique--especially in the perl debugger, wh
  • Okay this make me choke on my MD - "He's presently working for Amadeus, on an automated software testing application for their flight booking system."

    Also, lets see if we can debug the website and make that next button work......Not functioning in FF1.5/Win

  • by Anonymous Coward on Monday December 12, 2005 @02:41PM (#14240251)
    The only thing harder to spot in Perl is the good code. My rule of thumb is: If I can understand it easy in Perl, it's probably a bug.
  • Debugging perl? Doesn't that defeat the whole point?
  • by rodentia ( 102779 ) on Monday December 12, 2005 @02:42PM (#14240261)
    this symbol must be scalar.

    Unless the moon is gibbous.

    • Nah, it's easy to understand what's what, just have a look at my sig... =)

      PS I'm sorry if that perl oneliner doesn't work when you try it, but I'm taking the server offline for short periods of time while doing some upgrading... If it's down when you try it just try again a minute later.
  • by licamell ( 778753 ) * on Monday December 12, 2005 @02:47PM (#14240302)
    #! /usr/local/bin/perl
    # Two things that make debugging perl easy:

    use strict;
    use Data::Dumper;

    The first one will solve most peoples perl problems, and the second one is helpfull sometimes when dealing with complex datastructures.
    • The only time I used the debugger was to figure out why an update of a CPAN module suddenly misbehaved. I don't understand that people need a debugger at a weekly, or even daily basis. And I really don't understand the need for a book about it.

      I one was hired by a company that did a lot of C programming, and if there was something not working right, the rule was you had to fire up the debugger, and single step. I ignored that silly advice, and added a print statement, or reread my code.
      • [That's one freelance Perl programmer I'll have to remember never to hire.]

        Seriously, I'm one of those people who use a debugger every day. Actually, when I write new code in Perl, often the first thing I do is step through it in the debugger to make sure it does what I think it should. Especially in Perl, it is very easy to accidentally do something that's a little off. With the "wait until something goes wrong before I investigate" attitude demonstrated here, you'll never know anything is amiss until some
        • Actually, when I write new code in Perl, often the first thing I do is step through it in the debugger to make sure it does what I think it should.

          Excellent. A coder with the same ideals. I do this for Perl, and I did the same thing in C -- run it in the debugger, but only after a severe thrashing through PC-lint (Gimpel Software?) until it came out squeaky clean.

          Why? To make absolutely sure that the machine and I are in perfect agreement about what the expected behaviour is. It's time consuming, but bett

    • strict prevents you from doing some things with hashes which are valid code, so it came as a shock to once discover that strict itself was the bug. I hate how much of the stuff strict warns over doesn't stop the program from actualy working. It's like if the program would have ran fine anyway just run and be done with it so I can get on with my life. It's perl, it's not like it's ever going to be a piece of fine jewelry.
    • But what about this?

      use Coy; []

  • by Cherita Chen ( 936355 ) on Monday December 12, 2005 @02:53PM (#14240343) Homepage
    #!/usr/bin/perl $_='A=15; B=30; select(stdin); $|=1; select(stdout);$|=1; system "stty -echo -icanon eol \001"; for C(split(/\s/," 77.77 022.020.020 330.030.030 440.044.000 055.550.000 666.060.". "000")){D=0;for E(split(/\./,C)){F=0;for G(split("",E)){C[P][F++ ][D]=G} D++}J[P]=F; I[P++] =D}%L=split(/ /,"m _".chr(72)." c 2". chr(74)." a _m");sub a{for K(split(/ /,shift)){(K,L)=split(/=/,K );K=L{K};K=~s/_/L/; printf "%c[K",27}}sub u{a("a=40");for D(0..B -1){for F(0..A-1){M=G[F][D];if(R[F][D]!=M) {R[F][D]=M;a("m"."=". (5+D).";".(F*2+5)); a("a=".(40+M).";" .(30+M));print " "x2}}}a( "m=0;0 a=37;40")}sub r{(N)=@_;while(N--) {Q=W;W=O=H;H=Q;for F( 0 ..Q-1){for D(0..O-1) {Q[F][D]=K[F][D]}}for F(0..O-1){for D(0..Q- 1){K[F][D]= Q[Q-D-1][F]}}}}sub l{for F(0..W-1){for D(0..H-1){(K[ F][D]&& ((G[X+F][Y+D])|| (X+F=A)|| (Y+D>=B)))&& return 0}}1}sub p{for F(0..W-1){for D(0..H-1){(K[F][D]>0)&&(G[X+F][Y+D] =K[F][D]) }}1}sub o{for F(0..W-1){for D(0..H-1){(K[F][D]>0)&&(G[ X+F][ Y+D]=0)}}}sub n{C=int(rand(P)) ;W=J[C];H=I[C];X=int(A/2)-1 ;Y=0;for F(0..W-1){for D(0..H-1){K[F][D]= C[C][F][D]}}r(int(rand (4)));l&&p}sub c{d:for(D=B;D>=0;D--){for F(0..A-1){G[F][D]||next d}for(D2=D;D2>=0; D2--){for F(0..A-1){G[F][D2]= (D2>1)?G[F][D2-1 ]:0; }}u;}}a ("m=0;0 a=0;37;40 c");print "\n\n".4x" "." "x(A-4). "perltris\n".(" "x4)."--"xA."\n".((" "x3)."|"." "x(A*2)."|\n")xB .(" "x4). "--"xA."\n";n;for(;;) {u;R=chr(1); (S,T)=select(R,U,V, 0.01);if(S) {Z=getc;}else {if($e++>20){Z=" ";$e=0;}else{next;} } if(Z eq "k"){o;r(1);l||r(3);p}; if(Z eq "j"){o;X--;l||X++;p}; if (Z eq "l"){o;X++;l||X--;p};if(Z eq " "){o;Y++;(E=l)||Y--;p;E|| c |c|c|c|c|n||goto g;};if(Z eq "q"){last;}}g: a("a=0 m=".(B+8).";0 " ); system "stty sane"; '; s/([A-Z])/\$$1/g; s/\%\$/\%/g; eval;
  • I like to fire up the debugger via
    perl -d -e ';'
    which starts an interactive Perl debugger session. It's very useful for quickly seeing how snippets of code will behave.
  • Print statements (Score:3, Interesting)

    by Anonymous Coward on Monday December 12, 2005 @03:14PM (#14240531)
    As a result, some disheartened Perl coders eventually switch back to embedding "print" statements in their code. Fortunately, there is a better alternative

    Actually, after ~25 years of writing code, I've found that 'print' statements are the best alternative. I've used every kind of debugger and IDE in the past, but in the last couple of years I've found that I rarely use them.

    When you're in a debugger, you're down in the trees and it's hard to see the forest. With skillfully placed print statements that pick out the relevant data, stack traces for exceptions and a decent language, you can get a commanding overview of what's going on in your app. With a good editor, you can manipulate print statements just about as fast as breakpoints in an IDE, too. Just map a function key in your editor to "save file; make go".

    • Except that you can still use print statements (or System.Diagnostics.Debug.WriteLine, or whatever) in conjunction with a good IDE.

      In fact, the best IDEs allow you to have the value of a variable or expression printed every time a particular part of your code is hit, without modifying that code at all. (VS.NET, for instance.)

      In the end, you really shouldn't have to modify source code to figure out the value of variables at various points in the execution of that code.
  • older books (Score:2, Informative)

    by Anonymous Coward
    Thanks, I'd like to remind everybody that the 3 older books are still very worthwhile:

    Effective Perl, Hall and Schwartz
    Debugging Perl, Martin Brown
    Perl Debugged, Scott / Wright
  • debugging loops (Score:2, Interesting)

    by abiessu ( 74684 )
    I've found that debugging loops can be tedious in most of the 'normal' ways of going about it. I finally got sick of lots of 'print' output and discovered that using 'warn' statements and trapping the '__WARN__' signal (using a BEGIN) provided an especially effective method of debugging loops: store the warning text as the key of a hash where the value is incremented each time. Inside an END block, write the contents of the hash to your favorite stream.

    This method will debug loops of all kinds, and if eac
  • Watched variables (Score:4, Informative)

    by lewiscr ( 3314 ) on Monday December 12, 2005 @03:17PM (#14240554) Homepage
    > More specifically, watching a variable change value, while stepping
    > through the lines of a Perl script using the debugger, requires that
    > the programmer manually or programmatically echo that variable's value,
    > by issuing a print command ("p") followed by the variable name, one
    > way or another.

    $ perl -d -e 1
        DB h ...
        h [db_cmd] Get help on command w expr Add a watch expression
        h h Complete help page W expr|* Delete a/all watch exprs ...

    Admittedly, the watch expressions don't detect changes in deep data structures. But it works just find on dependant expressions. I'll regularrly set watches on a loop index and a data structure being indexed by said loop var. The watch expressions will display both results.

    In addition, the 'x' command works much better than 'p'. 'x' dumps the data structure, so it will display arbitrarily complex and deep data.

  • by talexb ( 223672 ) on Monday December 12, 2005 @03:20PM (#14240582) Homepage Journal

    I love the debugger -- my background is BASIC, assembler, C and finally Perl, so it fits right in with all those "programmning down to the bare metal" tools.

    However, a way cooler method is to use logging. The one I use these days is Log::Log4perl [], a terrific logger that you can turn on and off at will. Thus, if you have a bit of disk space, you can turn the knob up to 11 (DEBUG) and let the application go until you get to the Weird Bug. Then it's just a matter of pawing through the log files to find all of your excellent messages. Print statements sprinkled through the code? Please.

    And the bit about having to print the variable value every step in the debugger is a bit of a red herring .. you can set up commands that get executed before and after each step. Yes, it's a geeky thing to do .. that's why they call it Engineering.

  • Whenever I use the perl debugger, I find that I have to hit enter (after pressing n, or s) over and over, is there a way to tell it to do something x number of times, like n 5?
    • It's not exactly what you want, but "c <line>" will continue until hitting the line number given. Combined with "l" to list the code in the lines after the current line, this allows you get the effect you want. Another useful trick is setting conditional breakpoints: the syntax is "b <line|sub> <condition>". As always, the condition can be arbitrary perl code.

      • It doesn't work for loops though. The conditional breaking may help, but that means doing some thinking every time this situation comes up. Not the end of the world, but it's such a simple thing that I would hope the perl debugger could implement.
    • You can write a perl script to do that!

      Just redirect stdin and stdout to your script, fire up the program in debug mode and have your script feed it debug commands until something interesting (which of course you have predetermined) happens, or in response to your own input (you have of course saved the original stdin and stdout handles so you can still do io to your own program).

      Actually, I have only ever done this with gdb but I expect it will work with perl debug too.
  • by infinite9 ( 319274 ) on Monday December 12, 2005 @03:58PM (#14240887)
    Personally, I'm anti perl debugging.
  • by bcrowell ( 177657 ) on Monday December 12, 2005 @04:17PM (#14241051) Homepage
    For me, the real problems come when I'm debugging a Perl program that's linked to someone else's C library. I have an app [] that had been stable for a long time, until I found that with recent releases of Perl/Tk it suddenly started crashing once a week or so. A stack trace shows that it's crashing inside a certain C function in Perl/Tk, but my lack of C skills have stopped me from getting to the point where I could file a useful bug report. This is what I really need a book on. AFAICT, I would have to compile Perl/Tk myself using certain options, and the options that work for most C software don't actually seem to be the right ones for Perl/Tk. Then I would have to dust off my decades-old C and C debugging skills and figure out what was wrong. Ugh!
  • by Billly Gates ( 198444 ) on Monday December 12, 2005 @04:52PM (#14241339) Journal
    Barnes & Noble pays for references aka clicks just like amazon and the click links to his account.

    Also work4hire refers to his website to make his google page rank go up.
  • I've found myself lately using the open perl IDE ( []) for debugging. I can set breakpoints in it and trace variables in a little bar on the side. It isn't perfect--I don't know how well it works in a multithreaded environment in particular, but it has saved my ass many times. Of course it can't fix the "Not a SCALAR reference" crap when dealing with various data types, but that's where Perl 6 will fix things.
  • by rpg25 ( 470383 )
    Given that a big theme of the article is that graphical IDEs are better than the debugger for almost all purposes, it would be nice to have a list of some of these perl-capable IDEs so that we can assess the claim.
  • On the other hand, you might want to Forget [] the [] debugger [].

"If you lived today as if it were your last, you'd buy up a box of rockets and fire them all off, wouldn't you?" -- Garrison Keillor