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

I would like to be able to pass a subsitution command into a perl program and have it work. Below is a small snippit of code that doesn't work. I am setting the substitution string and then trying to use it later. It does not subsitute anything. Any help on how to do this correctly would be appreciated... Thanks Robert
#!/bin/perl my $SUBS='s/AA/BB/g'; $STR = "AAXXXAA"; $STR =~ $SUBS; print "$STR\n";

Replies are listed 'Best First'.
Re: substitution question
by jkahn (Friar) on Oct 17, 2002 at 18:20 UTC
    Looks like you need to use eval, since you have an executing context.
    my $SUBS='s/AA/BB/g'; $STR = "AAXXXAA"; eval "\$STR =~ $SUBS;"; print $STR, "\n";
    On the other hand, if you don't like eval:
    my $lh_sub = "AA"; my $rh_sub = "BB"; $STR = "AAXXXAA"; $STR =~ s/$lh_sub/$rh_sub/g; print $STR, "\n";
Re: substitution question
by Tanalis (Curate) on Oct 17, 2002 at 18:15 UTC
    You're almost there.

    When you're using a regular expression, the regexp itself can't be a variable (the contents between the / delimiters can). So, for the above:

    my $STR = "AAXXXAA"; $STR =~ s/AA/BB/g;

    Rather than assigning to the regular expression to a variable, then using the =~ operator on it, you need to apply the regular expression directly.

    If the contents of the regexp are going to change at runtime, you can place these into variables:

    my $sub_str = "AA"; my $sub_val = "BB"; my $str = "AAXXXAA"; $str =~ s/$sub_str/$sub_val/g;

    Hope this helps ..
    --Foxcub