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

Re: [perl #53504] Bug in if(open(my $fh,...)) { } scoping

Thread Previous
From:
Dr.Ruud
Date:
April 29, 2008 05:00
Subject:
Re: [perl #53504] Bug in if(open(my $fh,...)) { } scoping
Message ID:
20080429115312.9593.qmail@lists.develooper.com
Matt Sergeant schreef:
> # New Ticket Created by  Matt Sergeant
> # Please include the string:  [perl #53504]
> # in the subject line of all future correspondence about this issue.
> # <URL: http://rt.perl.org/rt3/Ticket/Display.html?id=53504 >
>
>
> 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.

I agree it is kind of an error.

That do{} needs a ";" at the end. But you can do without the do.

I frequently put an extra block around the file stuff:

    my $filename = "/etc/passwd";
    ...
    {   local $\ = "\n";
        open my $fh, "<", $filename or die "error with
'$filename':\n\t$!";
        ...
    }

such that the close() will happen automagically.

-- 
Affijn, Ruud

"Gewoon is een tijger."


Thread Previous


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