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?
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;
^ ^ ^^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With