Make friends with seek and tell, and use a linked list. Here's how:
  1. Your file will be composed of variable-length records.
  2. Each record will be appended to the end of the file, as nature intended.
  3. The first n bytes of each record will contain the packed address of the previously-written record.
  4. The first n bytes of the first record (i.e. the first n bytes of the file) will contain the address of the last-written record.
When writing a record,
  1. Read the address of the last record from the beginning of the file. Call it $last.
  2. seek to the end of the file.
  3. Use tell to see where you are. Call this address $next.
  4. Write $last to the end of the file, then your data record.
  5. seek to the beginning of the file, and write $next there.
When reading the file,
  1. Read $last from the beginning of the file.
  2. seek to the end of the file, and use tell to get the current address. Call it $next.
  3. seek to $last, and read n bytes into the variable $prev.
  4. Read $next - $last - n bytes from the file. This is the last unread record.
  5. Set $last = $prev and $next = $last.
  6. Repeat from step 3. until you've read as many records as you want, or until $last > $next (i.e. you've reached the beginning of the file).

    In reply to Re: writing to the top of a file by Dr. Mu
    in thread writing to the top of a file by Anonymous Monk

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



  7. Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  8. Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  9. Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  10. Please read these before you post! —
  11. 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
  12. 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;
  13. Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  14. See Writeup Formatting Tips and other pages linked from there for more info.