I would use the list-oriented nature of Perl and write the above as:
sub get_n_lines { my $fh = shift; grep defined($_), map {scalar <$fh>} 1..(shift); }
However before using this I would think carefully about whether I was ever going to read from a tty like STDIN tends to be. Try it with STDIN. Sure you get undef when the person indicates that they are done, but as you continue trying to read on the handle, it tries to read again.

For the vast majority of things I might use a function like the above for, that doesn't matter. But if I was in one of the remaining fraction of situations I would prefer to manually track whether or not I had hit the end of the file yet. (Issuing calls to eof can also trigger more reads.)

In fact the best general strategy that I know of for handling this kind of problem is to encapsulate the stream of a data into a structure that always keeps one row of data pre-fetched. Sure it is a lot of conceptual overhead to set that up. But it seems to work better in the end.


In reply to Re (tilly) 1: Get next 'n' lines from a file by tilly
in thread Get next 'n' lines from a file by tachyon

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.