http://qs321.pair.com?node_id=413802


in reply to Filehandles question

Perl closes all open file handle when it terminates normaly. I read somewhere that it should be better to let Perl this job instead of closing the files, but I don't remember exactly why. I hope someone else will point this out here later.

Replies are listed 'Best First'.
Re^2: Filehandles question
by rrwo (Friar) on Dec 10, 2004 at 20:33 UTC

    That's a safety feature, but it's better to close files when you're done with them:

    • It makes code maintenance cleaner, since it indicates that you are declaring that you are done with the file
    • Some operating systems (like Windows) have implicit file locking, so closing the file will release the lock and allow other processes to access the file.
    • On some operating systems, a limited number of files can be opened at a time. If you have a lot of processes running that leave files open that they don't need, nobody can open a file.
    • If there's an error or interrupt signal that kills your program, Perl may exit and leave the file open. If there's a lock, you've got a problem. In Windoze, you gotta reboot to clear the lock. Not something you want to do on a server.
    • Similarly, if the program is interrupted without an explicit close, output buffers may not be flushed and you lose data

    Open file handles shouldn't be treated like other variables in terms of garbage collection. The memory may be returned to the operating system when it exists, but Perl has no way of knowing for sure if it should be unlocked or the buffer flushed.... (there may be times where doing so can do more harm than good), so it won't do these things.

    If you don't want to be bothered with file opening and closing semantics, then use something like IO::All.