There are two three four potential approaches to this problem, but as it mostly sounds like homework to me, I'll only outline the general approaches:

The first approach is to observe that reverse(A+B) = reverse(B) + reverse(A), so you can split your long list into many smaller lists, reverse these smaller lists and then join the reversed lists back together. If you want to do this in an recursive approach, you could also observe that reverse(a) == a and treat that as a stopping condition, although that would be quite inefficient, as would be the observation that reverse(a+TAIL) == reverse(TAIL)+a.

The second approach, which works as long as you have enough core memory for storing a list of numbers, would be to read through the whole file, noting the offset of each line (as told via tell), and then to reverse that list of numbers, seek to each offset in the file and to then write out the line from there into the new file. If you are careful with your memory usage, or if you are tricky and store your offsets packed in a string, for example as 4-byte or 8-byte tuples, or maybe even as just the (presumed shorter) list of line-lengths, you can reduce the amount of memory you need to store the information and still reverse the whole file.

A third approach would be to not store any information and just seek a bit backwards from the current location and read data up to the current location, then scan for a line break. If one is found, output the line from there. Seek further backwards.

A fourth approach would be to use File::ReadBackwards.


In reply to Re: reversing files line by line by Corion
in thread reversing files line by line by naturalsciences

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.