Perl6 搜索然后替换为子例程的输出

Perl6 search then replace with output of subroutine

我已经梳理了文档,但我似乎找不到如何在 perl6 中执行此操作。

在 perl5 中我会这样做(只是一个例子):

sub func { ... }

$str =~ s/needle/func()/e;

即将 'needle' 替换为调用 'func'

的输出

好的,所以我们将从创建一个函数开始,该函数仅 returns 我们的输入重复 5 次

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

制作我们的字符串

my $s = "Here is a needle";

这里是替换

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

有几件事需要注意。因为我们只想匹配一个字符串,所以我们引用它。我们的输出实际上是一个双引号字符串,所以我们使用 运行 中的一个函数 {}。不需要 e 修饰符,因为所有字符串都允许这种转义。

The docs on substitution 提到 Match 对象放在 $/ 中,所以我们将其传递给我们的函数。在这种情况下,Match 对象在转换为 String 时只是 returns 匹配的字符串。我们得到了最终结果。

Here is a needleneedleneedleneedleneedle

Perl 6 中没有 e 修饰符;相反,右侧部分被视为 double-quoted 字符串。因此,调用函数最直接的方法是在函数名前加上一个&,并使用函数调用插值:

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

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

这导致 "I sew with a NEEDLE."。另请注意,捕获在 Perl 6 中从 0 开始编号,而不是 1。如果您只想要整个捕获的字符串,请改为传递 $/