Hi,
Dharshana Eswaran <[EMAIL PROTECTED]> wrote:
> Keeping the classic (state machine) approach in mid, i tried
> writing a logic for the same
>
> But i am not able to retrieve the lines accurately,
>
> Can you please help me with a small piece of code for the
> same logic which you mentioned?
This example uses an array as a ring buffer to store
previous lines from the input. It'll match lines that
contain the string "foobar".
$. contains the number of the current line read from the
last used file handle. This value is in the range of 1..n.
$howmany is the ring buffer size and determines how many
lines of text (including the match) are shown.
Sample usage (assuming you're saving this as linebuf.pl):
$ ./linebuf.pl < linebuf.pl
12: $buf[ $. % $howmany ] = $line;
13:
14: if( $line =~ m/foobar/ ){
#!/usr/bin/perl -w
use strict;
my @buf;
# number of context lines including matching line
my $howmany = 3;
while( my $line = <> ){
# store current line in ring buffer
$buf[ $. % $howmany ] = $line;
if( $line =~ m/foobar/ ){
# if we have a match, retrieve the previous
# lines from the ring buffer.
for( my $i = $howmany - 1; $i >= 0; $i-- ){
# number of the line we're retrieving
my $lineno = $. - $i;
# show fewer (or no) context lines for a match
# near (or at) the start of the input
next unless $lineno >= 1;
printf "%5d: %s", $lineno, $buf[ $lineno % $howmany ];
}
}
}
__END__
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/