Gary Gary - 3 months ago 11
Perl Question

If use a regex expression to match a string. Can I substitute another line?

If I use a regex expression to match a string, can I change a string in a different line? Basically, if

foo
exists, I want to change
bar
to
soap
.
bar
appears on a different line in a text file.
foo
, if present, will always appear before
bar
.

while (<FILE>) {
if (m/foo/){
s/bar/soap/;
}
}


Data file:

foo
food
red
bar
blue

Answer

When your if statement matches, the value of $_ has not yet changed. The line that m// has matched against is the same line that you are attempting to have s/// search-and-replace. Instead you need to set a flag that you can later check, once the new line has been hit:

open my $fh, '<', $filename or die "Cannot open $filename: $!\n";
my $flag = 0;
while (my $line = <$fh>) {
   $flag = 1 if $line =~ /foo/;
   $line =~ s/bar/soap/ if $flag;
}