Perl regular expression inside regular expression

expression, perl, regex

Solution

You certainly need the `e` modifier to be able to use

$str = 'banana';
$foo = 'na';
$str =~ s/$foo/$&=~s#.#-#gr/ge;
print $str;

See the online Perl demo

Note that the outer regex uses `/` regex delimiters, while the inner one contains different ones (you can use your favorite two here).

The `e` modifier is obligatory with the outer pattern, and you also need to pass `r` modifier to the inner one to avoid Modification of a read-only value issue.

Also note that before Perl v.5.20, you'd better avoid `$&` and enclose the whole pattern with `(...)` capturing group:

$str =~ s/($foo)/$1=~s#.#-#gr/ge;
          ^    ^ ^^ 

Problem

I would like to ask if it is possible to put another regular expression inside the RHS of a substitution match expression with the "e" modifier. For example, I would like to replace any occurrence of the word stored in $foo with the same number of "-", case insensitive. For example: ``` $str =~ s/($foo)/$temp = $1; $temp ~= s/./-//gie; ``` But it constantly gives syntax error when compiling, while ``` $str =~ s/($foo)/$temp = $1; $temp = "---"/gie; ``` does work. I guess I did not properly escape the slashes, any ideas?

Original source

Related problems