in reply to Uninitialized filehandles not as advertised?!

Since open already checks if the file exists and if it's readable, your sub would be better written as

sub RLS_ropen($) { my ($name) = @_; defined($name) or die "A file name must be supplied to RLS_ropen\n"; open(my $dbh, '<', $name) or return ''; return $dbh; } # end RLS_ropen

And it begs the question... Why do you need a sub at all? All there is in it is the call to open

Returning undef would be better than returning an empty string.

Replies are listed 'Best First'.
Re^2: Uninitialized filehandles not as advertised?!
by Anonymous Monk on May 26, 2008 at 19:59 UTC
    And die-ing on a failed open call would probably be better than returning something that some other piece of code may try to use as a filehandle and mysteriously barf on.
      Not at all. It's different, not better or worse. For example, open returns an error code and not an exception. Why should his open wrapper be any different?
Re^2: Uninitialized filehandles not as advertised?!
by Eli-Sko (Novice) on May 27, 2008 at 08:33 UTC

    ... Why do you need a sub at all?

    This code is part of an abstraction layer. Multiple programs will call this routine, which during the prototyping phase will just scan a flat file, but in future may use DBM or SQLite. As with abstraction layers in general, we won't want at that point to go back and change all of the open() calls to deal with database setup and take down.


    Returning undef would be better than returning an empty string.

    Answer 1

    I am lazy and prefer to use the simpler test with || instead of having to get my return value, separately test it for defined(), and only then start using it.

    Answer 2

    TMTOWTDI and I like it that way.

      Either || works for both undef and the empty string, or it works for neither. In this case, it works for both.

      TMTOWTDI means you have the freedom to choose the best way in a given situation. It doesn't mean it's a good idea to arbitrarily pick a way of doing something, contrary to the meaning you gave it. Returning undef results in a much better failure mode (gives an error with a meaningful message instead of a misleading warning) if the user forgets to do error checking, so returning undef is better than returning an empty string in this situation.