iPh*_*ian 15 regex evaluation replace string-substitution perl6
我已经整理了文档,但似乎找不到在perl6中执行此操作的方法。
在perl5中,我会做的(只是一个例子):
sub func { ... }
$str =~ s/needle/func($1)/e;
Run Code Online (Sandbox Code Playgroud)
即用对“ func”的调用输出替换“ needle”
Jon*_*ton 14
ePerl 6中没有修饰符。而是将右手部分视为双引号字符串。因此,最直接的调用函数的方法是&在函数名称前加上,并使用函数调用插值法:
# 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;
Run Code Online (Sandbox Code Playgroud)
结果是“我缝了针”。还要注意,捕获在Perl 6中从0开始编号,而不是从1开始。如果只需要整个捕获的字符串,则$/改为传递。
Sci*_*mon 11
好的,所以我们首先创建一个函数,该函数将返回的输入重复5次
sub func($a) { $a x 5 };
Run Code Online (Sandbox Code Playgroud)
做我们的弦
my $s = "Here is a needle";
Run Code Online (Sandbox Code Playgroud)
这是替换
$s ~~ s/"needle"/{func($/)}/;
Run Code Online (Sandbox Code Playgroud)
需要注意的几件事。因为我们只想匹配一个字符串,所以我们引用它。我们的输出实际上是一个双引号字符串,因此我们可以在其中运行一个函数{}。不需要e修饰符,因为所有字符串都允许这种转义。
替换文档中提到了Match对象,$/因此我们将其传递给函数。在这种情况下,Match对象在转换为String时仅返回匹配的字符串。我们得到了最终结果。
Here is a needleneedleneedleneedleneedle
Run Code Online (Sandbox Code Playgroud)