It's better to not open files until you need them. Personally, I think it's better to close them when you're done, but depending on the script it can be ok to leave them for the garbage collector. In my opinion that's just sloppy, but there are reasons to do it.
You can learn a lot about this from the open page alone.
What they do depends on the platform you're on. In *nix there are system calls that get made to the kernel requesting filehandles and readwrites and things. Perl buffers all this stuff and gives you a really nice interface (several actually) to use. In windows, I can only assume it's similar, but don't really know for sure. The details of system level IO represent an enormous discussion that you can safely ignore (for the most part) in perl.
| [reply] |
Filehandles are an operating system resource, and like other resources like RAM and active processes, are limited. Unless you free them yourself, they are freed for other users when your program exits.
Sometimes, it makes a lot of applicative sense to keep a filehandle open. For example, if you write to standard output or to your own log file, you probably shouldn't close and reopen the file on every write; that's just needless overhead. But in other occasions you're supposed to close a handle when you're done. With files there's sometimes also the consideration of locking. If another process wants to access the file but you've not only opened it but acquired an exclusive lock on it, the other process will have to wait for you to free.
For casual scripting, keeping a file open until your script ends, assuming it just runs for a few seconds, is probably okay. For anything else, you need to consider how you're using the resource. | [reply] |
You have already gotten good answers on why it is best to not open a filehandle before you need it, and why you should get in the habit of closing it when you are done.
Another advantage to closing the filehandle yourself rather than allowing the garbage collector to close it for you, is that you can check the return status. If all buffers could not be flushed when the close occurs, the only way you will know is if you run the close and check the status, like this pseudo-code:
close (FH) or die "Could not write all data to $file_or_pipe: $!";
| [reply] [d/l] |
One reason I like to use lexical filehandles is that they get automatically closed as soon as they go out of scope. So just remember to open your filehandle in the smallest scope that you need it in, and it will be garbage-collected and closed at the end of that block. (Unless you accidentally make a closure over it. I did that once. Oops.) | [reply] |