Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to do a cross-platform, atomic file replacement in Perl?

I have a very common situation. I have a file, and I need to entirely overwrite that file with new contents. However, the original file is accessed on every page load (this is a web app), so it can't be missing for very long. A few ms is OK (though not ideal), a second is not OK.

Right now I do this by writing a temp file to the same directory and then renaming that temp file to the name of the new file. I'm just using the normal File::Temp and "rename" to do this, in Perl. I was wondering--is there some other recommended/better way to do this? Preferably one that doesn't require a CPAN module, as this is the only place in my system that I need to do this, and I don't want a whole new dependency just for this.

Oh, and all of this has to work on Windows, Linux, BSD, OS X, Solaris, and most other common platforms.

Here is the code in question, for those interested.

like image 603
Max Kanat-Alexander Avatar asked Dec 24 '08 18:12

Max Kanat-Alexander


1 Answers

Your method seems just fine. It's quick, it's atomic, it uses core modules only, and File::Temp is a safe way to deal with temporary files. What more do you need?

like image 120
Adam Bellaire Avatar answered Nov 05 '22 14:11

Adam Bellaire