Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: When do filehandles close?

by beable (Friar)
on Jul 22, 2004 at 23:57 UTC ( #376759=note: print w/replies, xml ) Need Help??


in reply to When do filehandles close?

Just for completeness, one other time when filehandles close is when you call close() on them. Also, please take a look at open() in perlfunc, where it says this:

Using the constructor from the "IO::Handle" package (or one of its subclasses, such as "IO::File" or "IO::Socket"), you can generate anonymous filehandles that have the scope of whatever variables hold references to them, and automatically close whenever and however you leave that scope:

Replies are listed 'Best First'.
Re^2: When do filehandles close?
by gaal (Parson) on Jul 23, 2004 at 06:49 UTC
    You don't even need IO::File:
    { open my $fh, $file or die "open: $!"; $line = <$fh>; } # $fh is closed here

      Interesting... You made a little typo, that should be a semicolon on the end of the open() line. But look at this, it seems to solve pg's problem. And interestingly, IO::File has the same behaviour that pg is complaining about. Is this behaviour of $. a bug or a feature?

      #!/usr/bin/perl my $file = "pg-write3"; { open my $fh, $file or die "open: $!"; $line = <$fh>; $line = <$fh>; print "two reads:\t$.\n"; } # $fh is closed here print "closed file:\t$.\n"; { open my $fh, $file or die "open: $!"; print "open again:\t$.\n"; $line = <$fh>; print "one read:\t$.\n"; } # $fh is closed here print "closed again:\t$.\n"; __END__ Output: two reads: 2 closed file: 2 open again: 0 one read: 1 closed again: 1
        (Thanks for the typo spotting; fixed.)

        The $. behavior here is correct, if highly magical. Perl is keeping track of a property of an object that doesn't exist any more.

        (Or, looking at it another way, it's not magical at all: $. is a global that gets set whenever a filehandle is accesed. Even if the handle is closed, the global remains. But there's still something DWIMmish going on, because each (active) filehandle does remember its own line number, so that when you access two files in alternation, $. knows how to keep track.

        s/line number/record number/g for exactness.)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://376759]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (8)
As of 2022-12-05 11:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?