[ale] Perl Question

James Kinney jkinney at localnetsolutions.com
Mon Oct 16 19:50:47 EDT 2000



#!/usr/bin/perl
open (IN "</my/path/to/file")||die "$!\n";
@stuff=<IN>;
chomp (@stuff);

# Now for the fun part
# it's clunky, but it works

for ($i=0;$i<=$#stuff;$i++){
	if ($stuff[$i] =~ m/pattern/){push (@found, $i)}
}

#now you have an array of numbers corresponding to the array elements
#that match your pattern.

foreach $found (@found){
	print "$found[$found-1]\n$found[$found]\n$found[$found+1]";
}

# and now prints the line before, the line of, and the line after the
#match

Of course, as is always true in perl, there's more than one way to do it.

JimK
Local Net Solutions

On Mon, 16 Oct 2000, Ken Nagorski wrote:

> But checking the next line wasn't the problem, if the pattern matched I
> wanted to line above it and below it. See why redo didn't help? Even
> though I solved my current problem I would still love to know how to do
> this.
> 
> Ken
> 
> On 16 Oct 2000, Fletch wrote:
> 
> > >>>>> "Danny" == Danny Cox <danny at compgen.com> writes:
> > 
> >     Danny> Ken, On Mon, 16 Oct 2000, Danny Cox wrote:
> >     >> > I have a little perl problem, lets say I have a grep and it
> >     >> returns true.  > I want to not only print that line but I wanna
> >     >> print the line > below. Anyone know how I noght do this?
> >     >> 
> >     >> See the '-A' option to grep (at least, GNU grep).
> >     >> 
> >     >> grep -A1 'pattern' file
> >     >> 
> >     >> will do what you wish.
> > 
> >     Danny> 	Whups!  I missed the 'perl' part.  Well, you could use
> >     Danny> the system() function in the same way.
> > 
> >     
> >         Suguestions to use system to call grep from perl are almost as 
> > bad as using cat to pipe files to grep on the command line. :)
> > 
> > 
> > while( <> ) {
> >   if( /somepattern/ ) {
> >     my $nextline = <>;
> >     print $_, $nextline;
> >   }
> > }
> > 
> > 
> >         If you also want to check the next line for the pattern, then
> > stick a `redo' after the print.
> > 
> > 
> 
> --
> To unsubscribe: mail majordomo at ale.org with "unsubscribe ale" in message body.
> 

--
To unsubscribe: mail majordomo at ale.org with "unsubscribe ale" in message body.





More information about the Ale mailing list