Perl search and replace with variable and capture group

765 views Asked by At

As the question says, I am trying to do a search replace using a variable and a capture group. That is, the replace string contains $1. I followed the answers here and here, but they did not working for me; $1 comes through in the replace. Can you help me spot my problem?

I am reading my regular expressions from a file like so:

while( my $line = <$file>) {
    my @findRep = split(/:/, $line);
    my $find = $findRep[0];
    my $replace = '"$findRep[2]"'; # This contains the $1
    $allTxt =~ s/$find/$replace/ee;
}

If I manually set my $replace = '"$1 stuff"' the replace works as expected. I have played around with every single/double quoting and /e combination I can think of.

2

There are 2 answers

0
RobEarl On BEST ANSWER

You're using single quotes so $findRep[2] isn't interpolated. Try this instead:

my $replace = qq{"$findRep[2]"};
1
mpapec On

Why regex replacement when you already have your values in @findRep

while( my $line = <$file>) {
    my @findRep = split(/:/, $line);
    $findRep[0] = $findRep[2];
    my $allTxt = join(":", @findRep);
}