in reply to The Evolution of the Lowly Debug Statement

I've periodically started developing fancy debug/logging proceedures, but I find that I keep falling back on simple, semi-manual approaches like this:

($DEBUG) && print STDERR "The filename is $filename at line " . __LINE__ . "\n";

Where $DEBUG is a package variable that is either set at the top of the file as an embedded constant, or is set on the command line if "-d" is used (using Getopt::Std or the like).

I like having the ($DEBUG) at the front of each debug statement -- it's a visual reminder it's not part of the real code. Knowing what line number the message comes from is often useful, of course. Sometimes I prefix the messages with a $0 so you can see which program generated it.

Probably the fanciest thing that I do is for some code that I've been having trouble debugging (e.g. recursively defined algorithms), I'll begin every sub with the line:

my $sub = (caller(0))[3];
So my debug messages can always explain which sub generated the message.

In general though, I think techniques like this are a little cheesy, and it's usually better to think about how to use the perl debugger to solve the problem (note: this is admittedly a little harder to do with web-oriented code, but not impossible).

Update: Someone wrote to suggest that my techniques seem to be re-inventing features in the "Carp" module, but I don't quite agree.

Carp provides "cluck" and "confess" functions that generate full stack back traces, and these are great if you want back traces, but if you don't it clutters your debugging log tremendously.

Carp also has an interesting feature where you can run a script like this:

perl -MCarp=verbose script.pl
And automatically convert your "carp"s into "cluck"s with full back traces; that might seem easier to you than hand-rolling your own debug/verbose flags, but I personally prefer having hand-crafted ones that do whatever I want them to.