Hack #83. Write Your Own Warnings

Improve static code checking.

You have strict under control. You know why you use warnings. Maybe you even use B::Lint to find problems. Are they truly enough for you? If you've ever wished that you could make strict stricter or make warnings preachier, you're in luck.

Tip

Perl::Critic is a similarly excellent tool that audits your code based on Damian Conway's Perl Best Practices (O'Reilly).

The Hack

It's impossible to override some built-in functions[19] [Hack #91] like print( ) and printf( ). Usually print( ) succeeds because it writes to an internal buffer—but occasionally Perl has to flush the buffer. print( ) might fail if you write to a file on a full file system, to a closed handle, or for any of several other reasons. If you don't check print( ) and close( ) for success, you might lose data without knowing about it.

The best you can do for unoverridable functions is to create new warnings for unsafe code.

Here's bad_style.pl, a short program that opens a file and writes something to it. It has three misfeatures: ignoring the results of print( ) and close( ) and a terribly non-descriptive variable name:

open my $fh, '>>', 'bad_style.txt'
    or die "Can't open bad_style.txt for appending: $!\\n";
print {$fh} 'Hello!';
close $fh;

You could review every line of code in your system to find these errors. Better yet, teach B::Lint how to find them for you:

package B::Lint::VoidSyscalls; use strict; use warnings; use B 'OPf_WANT_VOID'; ...

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.