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:
- Are you sure your data is what you think it is?
- Are you sure your code is what you think it is?
- Are you inadvertently ignoring error and warning messages?
- Add the "stricture" pragmas (Use strict and warnings)
- Print the contents of variables
- 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)
- Dump arrays, hashes and arbitrarily complex data structures
- If you were expecting a reference, make sure it is the right kind (ARRAY, HASH, etc.)
-
Check to see if your code is what you thought it was: B::Deparse
-
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 $@;
- Demystify regular expressions using the CPAN module YAPE::Regex::Explain
- 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()) { ... }
use strict; use warnings; use diagnostics;
print "$var\n"; print "@things\n"; # array with spaces between elements
use Data::Dumper; print Dumper(\%hash); print Dumper($ref);
print ref $ref, "\n";
$ perl -MO=Deparse program.pl
# what the heck does /^\s+$/ mean? use YAPE::Regex::Explain; print YAPE::Regex::Explain->new('/^\s+$/')->explain();