in reply to Get next 'n' lines from a file
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.sub get_n_lines { my $fh = shift; grep defined($_), map {scalar <$fh>} 1..(shift); }
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.
|
|---|