0

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.

Community
  • 1
  • 1
dseiple
  • 530
  • 6
  • 16

2 Answers2

2

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

my $replace = qq{"$findRep[2]"};
RobEarl
  • 7,556
  • 6
  • 31
  • 48
1

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);
}
mpapec
  • 48,918
  • 8
  • 61
  • 112
  • To clearify, The replace string contains more than just `$1`. It can be any regular expression. I was just honing in on my issue. The replace values with therefore depend on what it matches on in `$allTxt`. The match criteria is specified in `$findRep[0]`. Setting `$findRep[0] = $findRep[2];` would overwrite that. – dseiple Sep 04 '13 at 16:23