in reply to Scoping question - will file handle be closed?
Well, for what it’s worth, here’s the approach that I take ... in any language that I write programs in ... whenever possible.
(1) I don’t pass file-handles around. Instead, I bury them as private variables in objects that are responsible for doing, on behalf of the application, anything that has to be done with [that type of ...] file. The very fact that there is a file involved, is buried as a concern of the object. When the object is destroyed, its destructor closes the file handle explicitly. Basically, the “reference count” of that file-handle never rises above one, and the handle is never cleaned-up by virtue of going out of scope. I handle everything.
(2) Every operating system uses buffering. Even if you ask the operating system to write all the data to disk (e.g. Unix/Linux sync()), there is no positive guarantee that it will actually happen, and it is quite an expensive thing to ask an operating system to do if it actually does do what you asked. There’s only one situation where I actually asked for this, and that was when I knew that the file-buffering system (SMARTDRV.EXE, which tells you how long ago it was) was buggy, and my program was intended to fix some of the consequences of that bugginess.
(3) Programming languages ... Perl included ... use their own per-line buffering system to assemble lines of output. You can rely upon them to flush those buffers before they close the file, but if you intend to write output that does not include the line-end sequence that they’re looking for, you might have to tell them to flush.