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

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

Thread Next
From:
Matt Sergeant
Date:
April 27, 2008 16:46
Subject:
bug in if(open(my $fh,...))
Message ID:
AF9AEB36-8351-4291-9751-CA79691FE6C4@sergeant.org
(I did post this via perlbug and to perlbug@perl.org but both appear  
to have gone into a black hole)

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.

(you can confirm with system(qq(ls -l /proc/$$/fd)) on Linux)

Using:

   do { my $fh;
   if (open($fh, "/etc/passwd")) {
     ...
   }
   }

Does the right thing and closes the file handle at the end of the  
scope, but that's ugly.

(confirmed on both 5.10 and 5.8)

Matt.

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