Perl6 search then replace with output of subroutine

Ok so we'll start by making a function that just returns our input repeated 5 times

sub func($a) { $a x 5 };

Make our string

my $s = "Here is a needle";

And here's the replace

$s ~~ s/"needle"/{func($/)}/;

Couple of things to notice. As we just want to match a string we quote it. And our output is effectively a double quoted string so to run a function in it we use {}. No need for the e modifier as all strings allow for that kind of escaping.

The docs on substitution mention that the Match object is put in $/ so we pass that to our function. In this case the Match object when cast to a String just returns the matched string. And we get as our final result.

Here is a needleneedleneedleneedleneedle

There is no e modifier in Perl 6; instead, the right hand part is treated like a double-quoted string. The most direct way to call a function is therefore to stick an & before the function name and use function call interpolation:

# An example function
sub func($value) {
    $value.uc
}

# Substitute calling it.
my $str = "I sew with a needle.";
$str ~~ s/(needle)/&func($0)/;
say $str;

Which results in "I sew with a NEEDLE.". Note also that captures are numbered from 0 in Perl 6, not 1. If you just want the whole captured string, pass $/ instead.