in reply to grab only if pattern matches previous line
I may be misunderstanding completely but it seems to me that if you re-word the question as "grab the next line if I get a match" then a cleaner (IMO) solution comes out. Also you did not say what to do if two consecutive lines match your pattern, should it be ignored or treated in the same way? Below are two solutions which handle each way. (you will need to adapt for your specific data)
my @lines = qw(foo foo2foo bar bar2bar baz2 bell bell1bell); print "Method 1\n"; for my $i (0..$#lines){ if ( $lines[$i] =~ /2/ ){ print "$lines[$i], $lines[$i + 1]\n"; } } print "\n\nMethod 2\n"; for (my $i=0; $i <= $#lines; $i++){ if ( $lines[$i] =~ /2/ ){ print "$lines[$i], $lines[$i + 1]\n"; $i++; } }
--
Do not seek to follow in the footsteps of the wise. Seek what they sought. -Basho
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: grab only if pattern matches previous line
by nkpgmartin (Sexton) on Jul 10, 2003 at 15:11 UTC | |
by greenFox (Vicar) on Jul 11, 2003 at 02:36 UTC |