hexcoder has asked for the wisdom of the Perl Monks concerning the following question:
When I read about JavaFans recursive regexps, I found it immediately fascinating. Then I realized all examples use the regexp to match something. No example showed how to use it in a substitution.
I wonder if it is possible to do transformations on a string based on a named recursive capture.
For example given
how do you change all (?&expr) to something like Expression($+{expr})?my $pat = qr { (?(DEFINE) (?<number> (?: [0-9]+ )) (?<sign> (?: [-+] )) (?<expr> (?: (?&term) (?: \s* [-+] \s* (?&expr))? )) (?<term> (?: (?&factor) (?: \s* [/*] \s* (?&term))? )) (?<factor> (?: (?&number) | (?&sign) \s* (?&factor) | \( \s* (?&expr) \s* \))) ) (?&expr) }x;
A suitable string could be '1+2*3' and the expected result would be Expression(Expression(1)+Expression(Expression(2)*Expression(3))).
Also interesting: how to substitute a subexpression like (?&factor).
Thanks! hexcoder
Edit: fixed a typo in the replacement text
Edit2: Better wording in the second question.
Back to
Seekers of Perl Wisdom