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);
Main Topics
Browse All TopicsI 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.
This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.
Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.
If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.
Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.
Access the answers to your technology questions today.
30-day free trial. Register in 60 seconds.
Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Try it out and discover for yourself.
30-day free trial. Register in 60 seconds.
Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.
Business Accounts
Answer for Membership
by: Perl_DiverPosted on 2006-06-08 at 11:18:03ID: 16863838
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.