Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

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 (Abbot)
on Jan 20, 2016 at 09:37 UTC ( #1153158=note: print w/replies, xml ) Need Help??


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.
  • Comment on 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.
  • Download Code

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1153158]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (3)
As of 2023-02-08 00:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I prefer not to run the latest version of Perl because:







    Results (40 votes). Check out past polls.

    Notices?