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,...))
(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


Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About