Link to home
Start Free TrialLog in
Avatar of lwinkenb
lwinkenb

asked on

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.
ASKER CERTIFIED SOLUTION
Avatar of Perl_Diver
Perl_Diver

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Perl_Diver
Perl_Diver

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);
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 - $_];

Avatar of ozo
use Tie::File;
 tie @array, 'Tie::File', 'filename' , autochomp=> 0 or die $!;
print @array[-10..-1];
File::ReadBackwards is also an option
Thanks for the grade and the points :)