in reply to Flocking

The polite approach has you request a shared lock for reading and an exclusive lock for writing. (That's LOCK_SH and LOCK_EX, respectively.)

On a non-braindead operating system, many processes can simultaneously acquire a shared lock on a file, but an exclusive lock can only be held by one, and it usually blocks until all other locks (including shared locks) are released.

You have a couple of options. You could open the file for read/write access with an exclusive lock, at the beginning of your program. That's conceptually simple, but you'll have to "rewind" it after reading, if you want to overwrite it. (See seek.) It also has the drawback that if another process has any lock on the file, your program will block (unless you work around it). This is the technique I'd choose.

You could also continue with the code above. If you don't close the filehandle explicitly, Perl will do that for you implicitly. Closing a filehandle has the side effects of flushing buffers and unlocking any locks on it.

I doubt your code to open the filehandle to a different file and acquire an exclusive lock is an atomic operation. (It probably takes more than one processor cycle to accomplish, so there is a possibility another process could jump in there and grab a lock. Of course, any process that doesn't check for locks could do that anyway.)

The best advice I can think of is to make sure that any other process that might access the file also use the same flock technique you decide on.

Disclaimer: I'm not as smart as I seem, sometimes.