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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: 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 Discipulus (Canon) on Jan 20, 2016 at 09:37 UTC | |
by mr_ron (Deacon) on Jan 21, 2016 at 11:01 UTC | |
|
Re^2: how to check for a word in a file... -- who spot the trick?
by Discipulus (Canon) on Jan 20, 2016 at 10:54 UTC | |
|
Re^2: how to check for a word in a file.. -- oneliner
by Discipulus (Canon) on Jan 20, 2016 at 11:38 UTC | |
|
Re^2: 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 BillKSmith (Monsignor) on Jan 21, 2016 at 03:30 UTC | |
|
Re^2: 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 ikegami (Patriarch) on Jan 22, 2016 at 16:45 UTC |