Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

Re: When do filehandles close?

by nothingmuch (Priest)
on Jul 23, 2004 at 13:02 UTC ( #376875=note: print w/replies, xml ) Need Help??

in reply to When do filehandles close?

This is, IMHO, one of the things in Perl that really wreaks of old age.

The issue here is when the FILE symbol in the symbol table is trashed. Since it is global, this happens only when the program exits (global destruction).

Exceptions to this are dynamically and lexically scoped file handles. With the traditional construct (open FILE simply creates FILE at the global scope) this is pretty voodoo.

{ local *FILE; # declare every FILE symbol ($FILE, @FILE, as well as + the handle) local open FILE, "<", "foo"; } print "open" if fileno(FILE); # nope.

What happens in that example is that all the symbols from file are recreated when local is called, and then the new versions exist in place of their predecessors, until they go out of scope. Then *FILE is rolled back, and the new values are destroyed. So in effect, the FILE filehandle is destroyed, and thus closed, and the nothing that was there before local is restored in it's place.

The "new" way to open filehandles, which exists from 5.8, is to pass an uninitialized lexical variable to open. I like this much better because it doesn't work with global symbols at all, and you don't have to use gensym from Symbol to generate "anonymous" filehandles.

{ open my $fh, "<", "foo"; print $fh "blah"; } # $fh is gone here

The IO::Handle family of modules implements further encapsulations - each file handle becomes an object.

To summarize, the filehandle is closed when the variable disappears, and probably the best way to get fine grained control of when variables disappear is to use variables that are not bound to global symbols, which aren't as flexible, but lexical ones. See Dominus's Coping with Scoping for more info on this.

zz zZ Z Z #!perl

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2022-12-03 22:22 GMT
Find Nodes?
    Voting Booth?

    No recent polls found