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
    Hi, I should probably clarify a couple things. 1. the data file is large. 2. there is a lot of useless header information and data I want to skip (some of it messy). 3. It is true that for each case where there is a request(REQUEST_NAME the very next line will always be the START_TIME, so really just incrementing one line past the good requests would work (though it's probably not as safe). 4. the BADSTRING is not the entire string. Thanks!

      If your data file is really large then you should work on the data as you slurp it. I used an array because that is what your sample code used :)

      while(<FILE>){ next if /^matches messy header/; chomp; if (/matches some string/){ my $next_line = <FILE>; # do something to $next_line here print "$_, $next_line\n"; } }

      --
      Do not seek to follow in the footsteps of the wise. Seek what they sought. -Basho