in reply to Exec'ing a regex stored in a scalar variable

$string =~ $regexp works if $regexp contains a regular expression. It doesn't in your case. "s/.../.../" is the Perl substitution operator, not a regular expression.

If given strings, the best way I can think of doing a substitution is:

$regexp = "a"; $subst = "b"; $global = 1; if ($global) { $string =~ s/$regexp/$subst/g; } else { $string =~ s/$regexp/$subst/; } # (?i...) can be used in $regexp for /.../i # (?m...) can be used in $regexp for /.../m # (?s...) can be used in $regexp for /.../s # (?x...) can be used in $regexp for /.../x # /g cannot be stored in $regexp, thus the need for $global. # /e cannot be stored in $regexp.

Replies are listed 'Best First'.
Re^2: Exec'ing a regex stored in a scalar variable
by Tanktalus (Canon) on Mar 11, 2005 at 22:43 UTC

    Depends on your amitiousness.

    $regexp = qr/a(b+)c/; $subst = 'c$1a'; my @a = $string =~ $regexp; $subst =~ s/\$(\d)/$a[$1-1]/ge; $string =~ s/$regexp/$subst/;
    Warning - untested. I know I've used code similar to this in the past with a limited amount of success. (i.e., it worked for me for what I needed it to work for, and this is not a cut&paste job of that code.)