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
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!
Are you posting in the right place? Check out Where do I post X? to know for sure.
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
Want more info? How to link or
or How to display code and escape characters
are good places to start.