|laziness, impatience, and hubris|
Re: When do filehandles close?by nothingmuch (Priest)
|on Jul 23, 2004 at 13:02 UTC||Need Help??|
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.
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.
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