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

Hi, I want to use scalar variables which store regular expressions while using string substitution. For Example:
$_ = "master442arb_ba"; $rule = "master\(.*\)arb_ba"; $action = "m\$1a_ba"; s/$rule/$action/; #s/master(.*)arb_ba/"m${1}a_ba"/; print $_;

The correct output is "m442a_ba". The commented s/// command gives the correct
output but if I try the same thing with the $rule and $action variables,
it gives "m$1a_ba" as the output. Can someone explain why and what would be the correct expression?

Thanks!

Replies are listed 'Best First'.
Re: Using scalar variables as substitution regular expression
by Anonymous Monk on Apr 05, 2009 at 08:46 UTC
Re: Using scalar variables as substitution regular expression
by baxy77bax (Deacon) on Apr 05, 2009 at 08:44 UTC
    or maybe this would be easier:
    $_ = "master442arb_ba"; $_ =~ /master(.*)arb_ba/; $action = "m$1a_ba"; s/$_/$action/; print $_;

      ... in which case you don't need the substition at all :)

      $_ = "master442arb_ba"; $_ =~ /master(.*)arb_ba/; $_ = "m$1a_ba"; print $_; # m442a_ba

      (the s/$_/$action/ in your snippet looks for "master442arb_ba" in "master442arb_ba" and replaces this (i.e. itself) with "m442a_ba" — an assignment is shorter...)

Re: Using scalar variables as substitution regular expression
by addy7de (Initiate) on Apr 05, 2009 at 08:35 UTC
    Got It!
    we can do it with "eval" as follows: $subst = "s/${rule}/${action}/"; eval ($subst) or die;