|
|
| more useful options | |
| PerlMonks |
Re^2: appending to html at beginning (updated)by haukex (Archbishop) |
| on Feb 03, 2017 at 08:34 UTC ( [id://1180937]=note: print w/replies, xml ) | Need Help?? |
|
Hi Discipulus, you open a tempfile, you write $new_lines to it then you open the existing original file for read and write it's lines to the temp one. Finally you swap files. I was considering posting this, but went with the Tie::File example instead. But since I happened to be working with code that uses the rename method just the other day, I had the basics handy, here it is:
For those who don't know, the advantage is that rename is an atomic operation on many filesystems, meaning that on such filesystems, the filename (in this case /tmp/test.txt) will always exist and always point to either the old version or the new version of the file, and never point to an "in-between" version where the file is still being written. Update: Forgot that unlink can set $!, so I preserved its value. Update 2: The code now modifies the file in the same way my other example does. Update 3, 2017-02-07: I was just reminded of the issue that files created by File::Temp have 0600 permissions, so I added the chmod to the code above. Update 2017-09-20: I provided an updated version of the above code using my new module File::Replace here: [RFC] File::Replace Regards,
In Section
Seekers of Perl Wisdom
|
|
||||||||||||||||||||||||||||||