1

I am inside a perl input file handle loop ,(while FH), and I need to perform search and delete operation to another file in the that loop.

I want to perform sed operation on a file from the loop and want to capture the output of command/sed to an array variable.

something like this:

@flops_ = `sed '/$clkname[-2]/d' occ.txt'` 

What should be the best way to this operation?

occ.txt:

/server/home/ramneek/kings/abc_occ/flop0/Q
/server/home/ramneek/kings/abc_occ/flop1/Q
/server/home/ramneek/kings/def_occ/flop0/Q
/server/home/ramneek/kings/def_occ/flop1/Q
/server/home/ramneek/kings/xyz_occ/flop0/Q
/server/home/ramneek/kings/xyz_occ/flop1/Q

abc,def, xyz are the variables. In each parent loop, clkname[-2] will get these variables. In each loop, I need to delete respective variable matching lines.

In 1st iteration of parent while loop, @flops_ should look like and array separated by \n charachter

/server/home/ramneek/kings/def_occ/flop0/Q
/server/home/ramneek/kings/def_occ/flop1/Q
/server/home/ramneek/kings/xyz_occ/flop0/Q
/server/home/ramneek/kings/xyz_occ/flop1/Q

In 2nd iteration @flops_ should be

/server/home/ramneek/kings/abc_occ/flop0/Q
/server/home/ramneek/kings/abc_occ/flop1/Q
/server/home/ramneek/kings/xyz_occ/flop0/Q
/server/home/ramneek/kings/xyz_occ/flop1/Q

and so on. TIA.

Håkon Hægland
  • 39,012
  • 21
  • 81
  • 174
  • *"I am inside a perl input file handle loop"* : It seems like the question is independent of the loop? You just need to change another file (not the file you are reading from now), right? – Håkon Hægland Oct 03 '21 at 15:37
  • Yeah. But I don't want to read another file (the one I want to change) inside the parent loop. So, I am looking for a system command to do the search and delete instead of reading file line by line. – Ramneek Singh Kakkar Oct 03 '21 at 15:39
  • Ok, can you give an example of the file `occ.txt` ? And from that what should be the contents of the `@flops_` array after the system call? – Håkon Hægland Oct 03 '21 at 15:42
  • Thanks for the update. What is the problem with the current `sed` command? It seems it shoud work fine, right? – Håkon Hægland Oct 03 '21 at 16:02

1 Answers1

3

The best way is to do it all in perl; read the lines of the file into an array once, and in your loop use grep to filter out the elements you don't want.

# read the lines of occ.txt into an array 
# (or use File::Slurper or Path::Tiny to do it)
open my $focc, "<", "occ.txt" or die "Couldn't open occ.txt: $!";
my @occ = <$focc>;
chomp @occ;
close $focc;

...;

while (<$fh>) {
    ...;
    # Filter out elements
    my @flops_ = grep { not /$clkname[-2]/ } @occ;
    ...;
}
Shawn
  • 47,241
  • 3
  • 26
  • 60