18.13. Semi-Automatic Debugging
Consider using "smart comments" when debugging, rather than warn statements .
Serialized warnings work well for manual debugging, but they can be tedious to code correctly. And, even with the editor macro suggested earlier, the output of a statement like:[*] Which is vital. If there's anything less enjoyable than beating your head against a bug for several hours, it's finally discovering that your debugging print statement was itself buggy, and the problem isn't anywhere near where you thought it was. This is presumably a homerbug.
warn 'results: ', Dumper($results);
still leaves something to be desired in terms of readability:
results: $VAR1 = bless( do{\(my $o = undef)}, 'Achievements' )
The Smart::Comments module (previously described under "Automatic Progress Indicators" in Chapter 10) supports a form of smart comment that can help your debugging. For example, instead of:
use Data::Dumper qw( Dumper );
my $results = $scenario->project_outcomes( );
warn '$results: ', Dumper($results);
you could just write:
use Smart::Comments;
my $results = $scenario->project_outcomes( );
### $results
which would then output either:
### $results: <opaque Achievements object (blessed scalar)>
or:
### $results: 'Achievements=SCALAR(0x811130)'
depending on whether $results is an actual object reference or merely its stringification.Smart::Comments also supports comment-based assertions:
### check: @candidates >= @elected
which issue warnings when the specified condition is not met. For example, the previous comment might print:
### @candidates >= @elected was not true at ch18/Ch18.049_Best line 23.
### @candidates was: [
### 'Smith',
### 'Nguyen',
### 'Ibrahim'
### ]
### @elected was: [
### 'Smith',
### 'Nguyen',
### 'Ibrahim',
### 'Nixon'
### ]
The module also supports stronger assertions:
### require: @candidates >= @elected
which prints the same warning as the ### check:, but then immediately terminates the program.Apart from producing more readable debugging messages, the major advantage of this approach is that you can later switch off all these comment-based debugging statements simply by removing (or commenting out) the use Smart::Comments line. When Smart::Comments isn't loaded, those smart comments become regular comments, which means you can leave the actual debugging statements in your source code without incurring any performance penalty.[*] If you needed them once, you'll almost certainly need them again.