You need to keep a buffer containing the lines you may need to throw away and print lines from the buffer when you know that they won't be thrown away. This stuff is tricky to get right because you have to correctly handle special cases for start up and ending conditions. Here's one way to do it:
use strict; use warnings; my $kPreLines = 1; my $kPostLines = 1; my $skipping; my @bufferedLines; while (defined (my $line = <DATA>) || @bufferedLines) { push @bufferedLines, $line if defined $line; while (@bufferedLines && $skipping) { shift @bufferedLines; --$skipping; } print shift @bufferedLines while @bufferedLines > $kPreLines + 1; next if !@bufferedLines; if ($bufferedLines[-1] =~ /XXXXX/) { $skipping = $kPostLines; @bufferedLines = (); next; } next if defined $line; print @bufferedLines; last; } __DATA__ QQQQQ PPPPP XXXXX is my name YYYYY KKKKK UUUUU BBBBB CCCCCC XXXXX is what I play KKKKK NNNNN
Prints:
QQQQQ KKKKK UUUUU BBBBB NNNNN
In reply to Re: how to check for a word in a file and if found remove that line, the above line and the below line from the file.
by GrandFather
in thread how to check for a word in a file and if found remove that line, the above line and the below line from the file.
by Ganesh Bharadwaj1
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |