http://qs1969.pair.com?node_id=1153158


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.
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.

I was sure it would be easier with splice but i falled in the 'modifying an array while iterating over it' pitfall..
To avoid a copied data I needed to undef some value and grep for defined values when printing the copy output.. anyway it works.
I have modified the DATA a little to be easier to follow
use strict; use warnings; my @lin = <DATA>; map { $lin[$_] and $lin[$_] =~/XXXXX/ ? $_ == 0 ? splice @lin,0,2,undef,undef : $_ == $#lin ? splice @lin,$_-1,2,undef,undef : splice @lin,$_-1,3,undef,undef,undef : 1 } 0..$#lin; print "$_" for grep {defined} @lin; __DATA__ XXXXX Aoooo XXXXX is my name Boooo 11111 22222 33333 Coooo XXXXX is what I play Doooo 44444 # OUTPUT 11111 22222 33333 44444


L*
There are no rules, there are no thumbs..
Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

Replies are listed 'Best First'.
Re^3: 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 mr_ron (Chaplain) on Jan 21, 2016 at 11:01 UTC

    If you are going to read the whole file into memory you also allow for the following solution which seems more simple and direct than working with splice.

    use strict; use warnings; my $file_content = do { local $/ = undef; <DATA>; }; $file_content =~ s/ (?:.*\n)? ^X{5}.*\n (?:.*\n)?//xmg; print $file_content; __DATA__ XXXXX Aoooo XXXXX is my name Boooo 11111 22222 33333 Coooo XXXXX is what I play Doooo 44444
    Ron