perl: print last 10 lines

I am searching through a file line by line:

foreach $line (<FILE>)
{
    if($line eq "something special")
   {
      here I want to print out the last 10 lines before $line
   }
}

I'm new to perl, so I wanted to check with the experts.  My guess on the best way to implement this is to use a queue of some kind.  Each time a line is read, add it to the queue.  When the queue is larger than 10 items, dequeue a line when a new one is added.

Is that the best way to accomplish this?  The file I will be reading has tens of thousands of lines, so I want to do this in the most efficient way possible.

Thanks.
LVL 5
lwinkenbAsked:
Who is Participating?
 
Perl_DiverCommented:
untested code, it might need some tweaking to get exaclty what you want:

my @queue = ();
foreach $line (<FILE>) {
   chomp($line); #<-- you may not need to chomp $line
   if ($line eq "something special")  {
     # here I want to print out the last 10 lines before $line
      print "$_\n" for @queue;
   }
   push @queue,$line; #adds current line to end of @queue
   shift @queue if (@queue > 10); #removes the first line from @queue if more than 10 lines are in @queue
}

Tie::File is also an option, but I am not sure if it would be any more efficient than the above scenario.
0
 
Perl_DiverCommented:
if you want to print the last 10 lines in order of highest line number  to lowest line number after "something special" is found  change this line:

print "$_\n" for @queue;

to:

print "$_\n" for (reverse @queue);
0
 
GnarOlakCommented:
If the file isn't too large to fit into memory:

open (IN, "<somefile");
@lines = reverse <IN>;
for (0..9)
{
    print $lines[$_];
}

If you want the lines in the original order then change the fifith line to this:

    print $lines[9 - $_];

0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

 
ozoCommented:
use Tie::File;
 tie @array, 'Tie::File', 'filename' , autochomp=> 0 or die $!;
print @array[-10..-1];
0
 
ozoCommented:
File::ReadBackwards is also an option
0
 
Perl_DiverCommented:
Thanks for the grade and the points :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.