This is a good example of a simple question which can have complex answers depending of the circumstances....
  1. Small files:
    perl -e "@l = <>; print 'first : ', $l[0], 'last : ', $l[$#l];" filen +ame
  2. This approach is only recommended for small files because all the lines are being read to an array (copying everything to memory before printing the lines)

  3. Medium sized files:
    perl -e "$first = <>; while($line = <>) { $last = $line; }; print 'fir +st : ', $first, 'last : ', $last;" filename
    This approach is recommended for medium sized files because it's reading one line at a time into memory.

    It's still not recommended for larges files because the entire file is being read. If you have a 4gbyte file and your I/O subsystem is only able to read 10 Mbytes/second you're going to take 400 seconds to get the answer.


  4. Really large files
    For really large files you can read the first line normally (see above). To read the last line, you have to:
    • seek to the end of the file
    • search for the line terminator of the line before the last
    • read from the position of the character after the line terminator to the end of file.

    Update: Use File::ReadBackwards . I didn't knew about this module and ended up reinventing the wheel (and ended up with a square wheel when compared with File::ReadBackwards :-)


  5. There's More Than Way To Do It,

    In reply to Re: Reading Lines from Text file by malduarte
    in thread Reading Lines from Text 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":



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