Perl updating a file in place
It does this by renaming the input file, opening the output file by the original name, and selecting that output file as the default for print() statements.The extension, if supplied, is used to modify the name of the old file to make a backup copy, following these rules: This is not quite what the OP asked. The original post asked for a way to edit a file in place, which this is.Example: If that is not what you want, you can avoid this behavior like so: #!At work I need to edit a file to add a comment character on some lines and also replace some multi-line strings with others. This module makes a file look like a Perl array, each array element corresponds to a line of the file.Tie:: File is very efficient; instead of rewriting the entire file, it just rewrites what is necessary to apply the modification you specify.But you could see How do I change one line in a file/delete a line in a file/insert a line in the middle of a file/append to the beginning of a file? This is a very nice thing if you're working on some rather large files.If the files are small this may be overkill.' construct are to be edited in-place.
So bonus points for that ;-) Unfortunately, while there are variations, there isn't really a better way of performing this trick. Another thing you may want to research is Tie:: File it'll allow you to edit files in the way you want but won't require you to read the entire file into memory.
My first take is to slurp all of the lines of the file into an array, edit the lines one by one, and then write out the array back to the file.
It seems to me that there should be a way to edit the file in place. You've reinvented one of the most common questions asked here.
This means you should not corrupt your input with the new output.
However, finding a program that does this is the problem.