The short answer is, no, not as easily as you might
think. Unlike say, word processing, you can't just go
to the start of the file, hit the 'insert' key,
and add a string: file editing is 'overwrite' mode
only. There are two basic ways to do it, and both
require you to read in all the data from the file
at some point.
- Open a new temporary file, add your string, then
open the old file. While reading from the old file,
write everything to the new file. Close both when
done, then turn the new file into the old file through
renaming.
This is the "general solution" mentioned
in the above link. It has the advantage of not using
much memory, as you only have to store one line at a
time in memory, instead of the whole file. It has the
disadvantages of using a temporary file, making the
renaming system calls, not working well with file
locking, and not being able to work with the data as
easily, although you can always read in the
whole file (@myfile = <ODLFILE>) at the cost of the
memory advantage mentioned above.
- A second way is to not use a temporary file, but just
open the file for reading and writing, slurping in
the whole file, make changes/add strings, rewind the
file via seek, then write the changed data back into
the file. One truncate and one close later, and
you are done.
This method has the disadvantages of
reading the whole file into memory, and perhaps being
harder for those not familiar with seek and truncate.
The advantages are not using a temporary file, not
having to rename, and a better ability to make
non line-by-line changes. It's also the best way to
do it if you are file locking.
I prefer the second way myself, but whatever floats
your boat - as long as it gets the job done!