Here's a slightly different approach that runs a while loop checking that end of file hasn't been reached rather than reading each line directly. Inside the loop a line is pushed onto the buffer then tested for the "reject" condition. If it is a reject then the next line is also added to the buffer then the whole buffer is discarded so as to reject all three lines. If the most recent line was not a reject then the previous line is shifted off the buffer and printed.
use strict; use warnings; open my $inFH, q{<}, \ <<EOD or die $!; XXXXX - additional test 1 XXXXX - additional test 1 ZZZZZ HHHHH - additional test 1 output expected PPPPP XXXXX is my name 1 XXXXX is my name 2 YYYYY KKKKK UUUUU BBBBB CCCCCC XXXXX is what I play KKKKK NNNNN ZZZZZ - additional test 2b XXXXX - additional test 2a QQQQQ - additional test 3 RRRRR - additional test 4 GGGGG XXXXX - additional test 5 XXXXX - additional test 5 EOD my @buffer; while ( not eof $inFH ) { push @buffer, scalar <$inFH>; if ( $buffer[ -1 ] =~ m{XXXXX} ) { last if eof $inFH; push @buffer, scalar <$inFH>; push @buffer, scalar <$inFH> while $buffer[ -1 ] =~ m{XXXXX} and not eof $inFH; @buffer = (); } else { print shift @buffer unless scalar @buffer == 1 and not eof $inFH; } } close $inFH or die $!;
The output.
HHHHH - additional test 1 output expected KKKKK UUUUU BBBBB NNNNN RRRRR - additional test 4
I hope this is of interest.
Update: Added the output.
Update: 2: Inserted push @buffer, scalar <$inFH> while ... line and added some paired "XXXXX" lines to address the point raised by mr_mischief. The output is unchanged.
Cheers,
JohnGG
|
|---|