Editing files inplace is tricky. One has to remember than on most
platforms, including UNIX and Windows, files are just sequences of
bytes. There is no line based datastructure. Your approach isn't
going to work,
unless the replacement part is the same
length (in bytes) as what you are replacing. But then you are still
missing a seek (you need to seek back to reposition the file pointer)
and a print.
There are two often used approaches for generic modifications:
- Read in the entire file into memory. Make the modifications,
seek back to the beginning of the file, and print the modified
content. Don't forget to perform a truncate, otherwise you
may end up with trailing garbage if the modified text is
smaller than the original. Obviously, this approach works
better for small files than huge files.
- Use a temp file. Read in parts (for instance lines) of the
original file, do the modifications, and write the modified
text to the temp file. If you are all done, move the temp
file to the original file.
You may want to use Tie::File, or investigate the
-i option of perl itself (or its $^I
equivalent).
Abigail