Categories
Uncategorized

Last 100 lines in a file

Yesterday, I had to pick out the last 100 lines in a file, for a small log viewer I was writing. Neither the Perl FAQ nor the Perl Cookbook had quite the right answer. So, this is what I ended up with.

sub last_lines {
  my ( $fh, $howmany ) = @_;
  my ( @lines, $i );
  while ( <$fh> ) {
    chomp;
    $lines[ $i++ ] = $_;
    $i = 0 if $i == $howmany;
  }
  return grep { defined }
    @lines[ $i .. $howmany - 1 ], @lines[ 0 .. $i - 1 ];
}

This is reasonably memory efficient, more so than the example I found which read the entire file in and then just picked the last $howmany items from the array.

The last line is interesting. We have to “swivel” the array around a partition point, in order to get the entries into the correct order. Also, we have to get rid of undefined entries. These crop up if you have less than $howmany lines in the file.

4 replies on “Last 100 lines in a file”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s