develooper Front page | perl.perl5.porters | Postings from April 2008

Re: bug in if(open(my $fh,...))

Thread Previous | Thread Next
From:
Matt Sergeant
Date:
April 28, 2008 12:28
Subject:
Re: bug in if(open(my $fh,...))
Message ID:
alpine.DEB.1.00.0804281925060.12136@bodger.sergeant.org
On Mon, 28 Apr 2008, Rafael Garcia-Suarez wrote:

> 2008/4/28 Matt Sergeant <matt@sergeant.org>:
>>  The following code:
>>
>>   if (open(my $fh, "/etc/passwd")) {
>>     ...
>>   }
>>
>>  Leaves the file open at the exit of the scope (in fact to the end of the
>> program). But $fh is out of scope, meaning the file should be closed.
>
> I think that's known. This is mostly because we want to allow this construct:
>
> if (my $x) { } elsif ($x) { }
>
> so, the $x is freed after the closing bracket of the if.

Yeah, that's bugged me before - I thought it might be related... But if 
the $x is freed there then why isn't the filehandle closed until program 
exit?

> A proper fix would be to add an "invisible" block around the if. That
> would slow down all ifs a bit, though.

I don't think that works either:

perl -Mstrict -le 'if (1) { if (open(my $fh, q(/etc/passwd))) { print 
"inner"; } } system(qq(ls -l /proc/$$/fd));'

Shows that the filehandle just isn't closed AT ALL (until program exit).

Matt.

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About