Hack #54. Debug with Comments

Let your documentation help you remove bugs.

There are two types of people who debug code: those who fire up Perl's built-in debugger and those who sprinkle print statements through their code. If you're in the second group, you probably know that one big problem with debugging by hand is that, once you remove the bugs, you have to go through and remove all the debugging statements as well.

What if you could safely leave them in the code? After all, if you needed them once, you'll probably need them again, when the next bug appears.

The Hack

"Something left in the code, but ignored" is pretty much the definition of a comment, so it's no surprise that you can use comments to turn off debugging statements. There's a much more interesting alternative, however: using comments to turn on debugging statements. The Smart::Comments CPAN module does just that: it turns comments into debugging statements.

Displaying variables

When you use Smart::Comments, any subsequent comment with three or more leading #s becomes a debugging statement and prints whatever the comment says to STDERR. For example, if you can't work out why your @play_calls variable is getting more elements than you expected:

my $call       = "26, 17, 22, hut!";
my @play_calls = split /\\s*,?\\s*/, $call;

insert some smart comments to report what's happening:

# make '###' magical... use Smart::Comments; my $call = "26, 17, 22, hut!"; ### $call my @play_calls = split /\\s*,?\\s*/, $call; ### @play_calls ...

Get Perl Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.