There are essentially two common ways, and both are probably doing the something similar behind the scenes.

The first way is to open the file for read-only, open a temp file for output, read line by line through the input file while writing line by line to the temp file. Then when you get to the point where you want to add something, write it to the temp file too. Then continue reading from the input file and writing line by line to the output file until the end of file is reached. Close both files. Rename the temp file so that it replaces the original file. Done.

The other common method is using Tie::File. This module allows you to treat the file as an array. And as you probably know (maybe), you can insert items into the middle of an array by using splice. You can also push, pop, shift, and unshift an array. And, you can modify the contents of any of the array's existing elements. As you do this, all the grunt work of temp files, etc., goes on behind the scenes so you don't have to worry about it.

The reason that you cannot write (easily) to the middle of a file is that a file is a single long contiguous string written to a storage device. If you write to the middle, you overwrite what's already there; the OS doesn't have any idea how to insert, just overwrite. Also, files themselves don't have any concept of lines; that's a level of abstraction that Perl offers you for convenience. This is an oversimplification, but essentially sufficient to paint the picture.


Dave


In reply to Re: How Do I Add text to certain parts of the file? by davido
in thread How Do I Add text to certain parts of the file? by EchoAngel

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.