A common idiom would also be to open a tempfile with a sufficiently randomized name (see File::Temp, do your writing there, and then after obtaining a lock on the output file, rename or move the tempfile into place over the output file. (emphasis added)
Race condition waiting to happen (at least as I am reading your statement). Have the lock signal the ability to modify the file (lock first, write second). If you don't lock first, you risk clobbering someone else's changes:
- You create a tmp file
- They create a tmp file
- They lock
- They overwrite
- They unlock
- You lock
- You overwrite
- You unlock
The changes made by "They" are now gone. Lock before read just to ensure that you have the newest data. Otherwise, I agree.