Regexes & grammars

Substitution with a closure

Full

Replace each match with the result of running code on it.

The replacement side of .subst (or s///) can be a closure instead of a fixed string — it runs per match and its return value is substituted. This turns find-and-replace into find-and-transform.

Compute the replacement #

The block receives the match as $/; here each digit is doubled.

say "a1b2c3".subst(/\d/, -> $/ { $/ * 2 }, :g);
Output
a2b4c6

A method as the replacement #

A Whatever/method form works too — *.tc title-cases each matched word.

my $s = "hello world";
say $s.subst(/\w+/, *.tc, :g);
Output
Hello World

Notes #