in reply to Regex question

Keep an array of the last lines read:

#!/usr/bin/perl use Getopt::Std; my %o; getopt 'b:a:',\%o; my $pat = shift; my @last; while(<>) { if (/$pat/) { @last = (); <> for 1..$o{a}; next; } push @last, $_; print shift @last if $o{b} < @last; } print @last;

Replies are listed 'Best First'.
Re^2: Regex question
by ikegami (Patriarch) on Jan 26, 2009 at 13:15 UTC
    That will fail if you have two matches within "A" lines of each other
    01 keep 02 discard B5 03 discard B4 04 discard B3 05 discard B2 06 discard B1 07 somepat 08 discard A1 09 somepat 10 discard A1 11 discard A2 <- Not dicarded 12 discard A3 <- Not dicarded 13 keep

      Okaay... that will do:

      #!/usr/bin/perl use Getopt::Std; my %o; getopt 'b:a:',\%o; my $pat = shift; my @last; OUTER: while(<>) { if (/$pat/) { @last = (); for my $i(1..$o{a}) { $_ = <>; redo OUTER if /$pat/; } next; } push @last, $_; print shift @last if $o{b} < @last; } print @last;