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

Hi, I'm trying to write an application that takes 2 regular expressions as input, and then do a substitution on a file. The problem happens when I try to use the memory variable as the second substitution. The resulting output becomes the literal '$1' as opposed to the match in parenthesis. It's better to look at the code.
my ($reg, $reg2) = @ARGV; my $string = "how1=on&how2=on"; $string =~ s/$reg/$reg2/eg; print $string;
Input: perl test.pl how(\d)=on why$1=off
What I want the ouput to be is: why1=on&why2=on
What I actually get is: why$1=off&why$1=off.
Any help is greatly appreciated!
Thanks,
Nathan

Replies are listed 'Best First'.
Re: Help with Regexp substitution using variables
by ikegami (Patriarch) on Jan 20, 2005 at 02:48 UTC

    The following works, but you risk injecting commands into your script. To do it properly, you'd have to do the variable interpolation yourself.

    my ($reg, $reg2) = @ARGV; my $string = "how1=on&how2=on"; $string =~ s/$reg/ eval "\"$reg2\"" /eg; print $string;
      Or
      $string =~ s/$reg/qq{qq{$reg2}}/eeg;

      Caution: Contents may have been coded under pressure.
        I like making the eval EXPR evident over adding a second /e, because of the inheritant risks to using them.
Re: Help with Regexp substitution using variables
by Ardemus (Beadle) on Jan 20, 2005 at 04:13 UTC
    I don't have have an answer, but I can give you some information to make it easier to find. You need recursive variable interpolation. The /e in your regex stands for eval. It executes the result as perl code (see taint checking if you want to start looking into security). Naturally, the evaluation of $reg2 is its contents.

    You can use /ee to eval results of the first eval (as Dave suggested). In fact, I believe that you can add 'e's to recursively evaluate as many iterations as you want. For example:

    > perl -e "$string='ReplaceMe';$s1='Bug';$s2='$s1';$s3='$s2';$string=~ +s/Me/$s3/eeeg;print $string" > ReplaceBug
    I hope this helps.
      Wow, thanks for the quick replies, everyone! I didn't know you could keep adding 'e' to a reg. pretty cool
Re: Help with Regexp substitution using variables
by dave_the_m (Monsignor) on Jan 20, 2005 at 02:50 UTC
    $string =~ s/$reg/'"'.$reg2.'"'/eeg;
    is one of many possibilities

    Dave.