in reply to Re^3: averages from multiple files
in thread averages from multiple files
From reading your post, I'm not sure that the points about "my" and file handles is completely clear. You clearly see that a re-open on the same file handle closes the previous file.
In the first foreach loop() for reading, my $handle is already closed before he gets to the point of opening that handle for write! This is a good thing. In your code that is not true. To do the same thing, you would need an explicit close() after the reading loop.
I would have gone further and used a name like "my $infile" in the first loop and a different name, like "my $outfile" for the output file.
Whether or not to close a file when the program is going to end shortly (very short time - some milliseconds) is a minor quibble.
One main reason to do this is that file handles are limited resources and closing a file handle frees resources - there will even be a limit to the maximum number of files that the entire system can have open at one time - albeit large as that limit is. However short of an OS fault (crash), leaving a file handle open for a very short time causes no harm. If the program is going to run for a significant time after you are finished with a file, I would close it. Making these judgements is part of the art of programming.
The rule that I use that the level of the program that opens a file is responsible for closing it. Open it in a loop, close it in that loop. Open it in a sub, close in that sub.
Early in my career, I saw one program run for 5 days and then fail because an open for the output file failed! So handling these situations can definitely have impacts!
I am an absolute fan of the use of "my" to scope variables to the smallest area possible. kennethk's code just has %data and the last use of $my handle at the file level scope. You have lots, like $key is "re-used".
A big advantage of using "my" is that you can "cut-n-paste" code into new programs without having to worry about "spooky unforeseen action at a distance".
|
|---|