in reply to RFC: "Best Practices" code review section

I use something like this:

package OpenOrDie; use strict; use warnings; use vars '@ISA @EXPORT $VERSION'; require Exporter; $VERSION = '0.30'; @ISA = 'Exporter'; @EXPORT = 'Open'; sub Open { my ($mode, $file) = @_; open my $fh, $mode, $file or die("Unable to open file '$file' using mode '$mode': $!") return $fh; }

Which I then use like:

use OpenOrDie; my $FILE = Open('<',$filename);

This also means I can catch the error consistently:

eval { my $FILE = Open('<',$filename); }; if ($@) { warn("Cannot parse configuration; $@"); $config{skip} = 1; }
<-radiant.matrix->
Larry Wall is Yoda: there is no try{} (ok, except in Perl6; way to ruin a joke, Larry! ;P)
The Code that can be seen is not the true Code
"In any sufficiently large group of people, most are idiots" - Kaa's Law

Replies are listed 'Best First'.
Re^2: RFC: "Best Practices" code review section
by merlyn (Sage) on Aug 15, 2005 at 20:21 UTC

      No.

      Fatal overrides open; overriding I/O functions has been prohibited by coding standards nearly everywhere I've worked.

      Also, the above is very much simplified from the live module I use (NDA and all that, can't be too careful): my actual code calls out to Log::Log4Perl and optionally calls out to Carp's croak or carp functions, falling back to warn if these can't be found.

      AFAIK, Fatal doesn't do those things. Besides, even if I didn't have those requirements, most code I write falls under requirements such that CPAN modules must be used as-installed (no modification): since the functionality I require is so easy to duplicate, better to have it in a module I can actually extend later.

      <-radiant.matrix->
      Larry Wall is Yoda: there is no try{} (ok, except in Perl6; way to ruin a joke, Larry! ;P)
      The Code that can be seen is not the true Code
      "In any sufficiently large group of people, most are idiots" - Kaa's Law
      Was Fatal too complicated, or something? After all, that's core now.

      I've worked places where something like this was the preferred style. The argument went (and I think it's at least vaguely reasonable) that by using a different subroutine you could tell by looking at the code in question whether an exception would be thrown - rather than having to look at the top of the file for the use Fatal. It also had the advantage of breaking at runtime if you forgot to load the 'safe' module - whereas forgetting to load Fatal.pm meant the code continued to 'work'.