Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: When do filehandles close?

by nothingmuch (Priest)
on Jul 23, 2004 at 13:02 UTC ( [id://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.

-nuffin
zz zZ Z Z #!perl

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2024-03-29 05:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found