http://qs321.pair.com?node_id=744845

Update: The updated version of this Meditation is at Re: RFC: Basic debugging checklist (updated) and the Tutorial version is now at Basic debugging checklist. Here is the untouched original:


Before I post this as a Tutorial, please help me to improve this by offering constructive feedback.

Are you new to Perl? Is your program misbehaving? Not sure where or how to begin debugging? Well, here is a concise checklist of tips and techniques to get you started.

This list is meant for debugging some of the most common Perl programming problems; it assumes no prior working experience with the Perl debugger (perldebtut). Think of it as a First Aid kit, rather than a fully-staffed state-of-the-art operating room.

These tips are meant to act as a guide to help you answer the following questions:

  1. Add the "stricture" pragmas (Use strict and warnings)
  2. use strict; use warnings; use diagnostics;
  3. Print the contents of variables
  4. print "$var\n"; print "@things\n"; # array with spaces between elements
  5. Check for unexpected whitespace
    • chomp, then print with colon delimiters for visibility
      chomp $var; print ":$var:\n";
    • Check for unprintable characters and identify them by their ASCII codes using ord
      print ":$_:", ord($_), "\n" for (split //, $str)
  6. Dump arrays, hashes and arbitrarily complex data structures
  7. use Data::Dumper; print Dumper(\%hash); print Dumper($ref);
  8. If you were expecting a reference, make sure it is the right kind (ARRAY, HASH, etc.)
  9. print ref $ref, "\n";
  10. Check to see if your code is what you thought it was: B::Deparse

  11. $ perl -MO=Deparse program.pl
  12. Check the return (error) status of your commands

    • open with $!
      open my $fh, '<', 'foo.txt' or die "can not open foo.txt: $!";
    • system and backticks (qx) with $?
      if (system $cmd) { print "Error: $? for command $cmd" } else { print "Command $cmd is OK" } $out = `$cmd`; print $? if $?;
    • eval with $@
      eval { do_something() }; warn $@ if $@;
  13. Demystify regular expressions using the CPAN module YAPE::Regex::Explain
  14. # what the heck does /^\s+$/ mean? use YAPE::Regex::Explain; print YAPE::Regex::Explain->new('/^\s+$/')->explain();
  15. Checklist for debugging when using CPAN modules:
    • Check the Bug List by following the module's "View Bugs" link.
    • Is your installed version the latest version? If not, check the change log by following the "Changes" link.
    • If a module provides status methods, check them in your code as you would check return status of built-in functions:
      use WWW::Mechanize; if ($mech->success()) { ... }