views:

67

answers:

1

I am trying to do a search and replace with variables. In this case variables that I pulled from a previous match. Here is my code:

$fileContentToAlter =~ s/$2/$1/g;

Now I realize in that state, it is being read incorrectly as $ has its own meaning inside of a regexp. I did some searching on the web and read that doublequotes could fix the problem as it would interpolate but that doesn't seen to work for me. I'm not going to lie, this is a homework assignment so I am not expecting a flat out answer. Just a nudge in the right direction.

+4  A: 

Avoid '$1' and '$2' because they are regex metacharacters.

use strict;
use warnings;

my $val1 = "abc";
my $val2 = "def";
while (<>)
{
    s/$val1/$val2/g;
    print;
}
Jonathan Leffler
Thanks for the help. I was starting to wonder if I should just create variable to assign my $1 and $2 results to.
Pinsickle