[ale] Perl Question

Fletch fletch at phydeaux.org
Mon Oct 16 15:38:41 EDT 2000


>>>>> "Ken" == Ken Nagorski <kenn at pcintelligent.com> writes:

    Ken> But checking the next line wasn't the problem, if the pattern
    Ken> matched I wanted to line above it and below it. See why redo
    Ken> didn't help? Even though I solved my current problem I would
    Ken> still love to know how to do this.


my $prevline = '';
while( <> ) { 
  if( /somepattern/ ) { 
    my $nextline = <>; 
    print $prevline, $_, $nextline;
    $prevline = $_; $_ = $nextline; 
    redo
  } else {
    $prevline = $_
  }
}

        You can change $prevline to @prevlines and use shift and push
to generalize this for remembering more than just one line (i.e. the
last n lines).


        Or for small enough files (or where you have gobs of swap for
large files) and you don't mind slurping it all into RAM:


my @lines = <>;

print @lines[0,1] if $lines[0] =~ /somepattern/;

foreach( 1 .. $#lines-1 ) {
  print @lines[ $_-1 .. $_+1 ] if $lines[$_] =~ /somepattern/;
}

print @lines[-2,-1] if $lines[-1] =~ /somepattern/;

-- 
Fletch                | "If you find my answers frightening,       __`'/|
fletch at phydeaux.org   |  Vincent, you should cease askin'          \ o.O'
678 443-6239(w)       |  scary questions." -- Jules                =(___)=
                      |                                               U
--
To unsubscribe: mail majordomo at ale.org with "unsubscribe ale" in message body.





More information about the Ale mailing list