Section 13.2. Builtin Failures


13.2. Builtin Failures

Make failed builtins throw exceptions too.

Given that exceptions are the recommended way of signaling and handling errors, Perl's own builtins pose something of a problem: they rely on special return values or flag variables instead.

Ignoring the return values of builtins makes for prettier, but much less robust, code:

     open my $fh, '>', $filename;     print {$fh} $results;     close $fh;

As it turns out, though, it's much easier to change how Perl's builtins fail than it is to change how Perl programmers code. You just need to use the standard Fatal module:

      use Fatal qw( open close );     open my $fh, '>', $filename;     print {$fh} $results;     close $fh;

The Fatal module is passed a list of builtins and, by the use of dark and terrible magics[*], it transforms those functions so that they no longer return false on failure; they now throw an exception instead. This means that the last three untested lines of the previous example are now perfectly acceptable. Either each builtin will succeed, or one will fail, at which point that builtin will throw an exception.

[*] These are well worth studying if you're brave enough to delve into the source of Fatal.pm.

use Fatal can also be applied to subroutines, to convert them from return-false-on-failure to throw-exception-on-failure. For example, in the previous guideline, instead of rewriting locate_and_open( ), you could have Fatal'd it:

      # Load subroutine to find and open a file by name     # (Unfortunately, we're stuck with using the original version,     #  which returns false on failure.)     use Our::Corporate::File::Utilities qw( locate_and_open );     
# So change that unacceptable failure behaviour to throw exceptions instead...
use Fatal qw( locate_and_open );
# and later...
for my $filename (@source_files) { my $fh = locate_and_open($filename);
# Now throws exception on failure
my $head = load_header_from($fh); print $head; }



Perl Best Practices
Perl Best Practices
ISBN: 0596001738
EAN: 2147483647
Year: 2004
Pages: 350
Authors: Damian Conway

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net