Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Have an issue with Substitutions. I have a config file that holds all my regular expressions. Problem is the subsitutions don't work. Example:
$text = 'Cheese.Bacon'; $v1 = '(\w+)\.(\w+)'; $v2 = '$2\.$1'; $test =~ s/$v1/$v2/;
The end result should be:
$text = 'Bacon.Cheese';
This is what I get:
$text = '$2\.$1';
How do I get the Substitutions to work correctly.

Thanks in advance.

Edit by tye, title, remove BR tags, add CODE tags

Replies are listed 'Best First'.
Re: RegEx - Using Templetes
by Zaxo (Archbishop) on May 29, 2003 at 02:48 UTC

    You have several problems there. Your substitution string must be evaluated twice to get the $1 and $2 interpolated. Evaluation, however, does not like the regex style backwhack in $v2, and will simply take a bare dot to mean concatenation. Modify your code to something like this:

    $text = 'Cheese.Bacon'; $v1 = qr/(\w+)\.(\w+)/; $v2 = 'qq($2.$1)'; $text =~ s/$v1/$v2/ee;
    I added use of qr() for $v1, but what you had was ok.

    After Compline,
    Zaxo

      You guys are awesome. the qq{...} worked perfectly. Thanks so much!
Re: RegEx - Using Templetes
by Enlil (Parson) on May 29, 2003 at 02:54 UTC
Re: RegEx - Using Templates
by VSarkiss (Monsignor) on May 29, 2003 at 02:44 UTC

    The easiest thing is to use the /e modifier: $text =~ s/$v1/$v2/e;Read more about it in perlre.

    Update
    This is wrong; follow Zaxo's advice below.