develooper Front page | perl.perl5.porters | Postings from June 2009

Re: improving $! usability

Thread Previous | Thread Next
Michael G Schwern
June 25, 2009 00:35
Re: improving $! usability
Message ID:
H.Merijn Brand wrote:
> On Sun, 21 Jun 2009 07:22:45 -0400, Michael G Schwern
> <> wrote:
>> What I was thinking was something like:
>>     open my $fh, "<", $file or die $fh->error;
> this is *very* counter-intuitive.
> After a fail, I expect $fh to be false. How do I call a method on an
> undefined value?

false != undefined.  $fh can be false and yet still be a valid object.  It
represents a filehandle which failed to open.  I don't think the open() docs
say they will leave $fh untouched on failure.

Here's an expansion of what open() is conceptually doing:

	my $fh = IO::File->new;
	$fh->open("<", $file) or die $fh->error;

After all, its not open's return value that we're checking.  Its making an
IO::Handle object.  The reason it seems so odd is we don't think of
filehandles as objects, but they are.

And its the most logical place to attach the error to.  Its an error about
failing to open that filehandle.  Otherwise you need an unassociated global
which is what got us into this mess in the first place.

>>     while (<$fh>) {
>>         print;
>>         }
>>     die $fh->error if $fh->error;
> Here, I like it

Don't try the paranormal until you know what's normal.
    -- "Lords and Ladies" by Terry Prachett

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About