Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: print line 5 lines previous to comaprison line!

by davorg (Chancellor)
on Jun 07, 2001 at 16:51 UTC ( #86529=note: print w/ replies, xml ) Need Help??


in reply to print line 5 lines previous to comaprison line!

You don't say what to do if the match is found in the first five lines of the file. I'm going to assume that this can't happen. I'm also going to assume that you don't want to read the whole file into memory at once.

I'd build a buffer that always contains the previous five lines and work with that. Something like this:

#!/usr/bin/perl -w use strict; my @buffer; push @buffer, scalar <DATA> for 1 .. 5; my $pat = 8; # adjust to value to search for while (<DATA>) { print $buffer[0] if /$pat/; push @buffer, $_; shift @buffer; } __END__ 1 2 3 4 5 6 7 8 9 10
--
<http://www.dave.org.uk>

Perl Training in the UK <http://www.iterative-software.com>


Comment on Re: print line 5 lines previous to comaprison line!
Download Code
Re: Re: print line 5 lines previous to comaprison line!
by Adam (Vicar) on Jun 08, 2001 at 01:47 UTC
    Nice. One suggestion:
    # change: print $buffer[0] if /$pat/; # to: print $buffer[0] if /\Q$pat\E/o;
    The \Q and \E presume that $pat is just a string, not a regex. So you would want to escape any special characters (like '.' or '+' ) and the o tells Perl that $pat isn't going to change in the loop, so it won't keep recompiling the pattern.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://86529]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (8)
As of 2014-09-19 04:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (129 votes), past polls