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.
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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 - $_];
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 - $_];
use Tie::File;
tie @array, 'Tie::File', 'filename' , autochomp=> 0 or die $!;
print @array[-10..-1];
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 :)
print "$_\n" for @queue;
to:
print "$_\n" for (reverse @queue);