Raku:在正则表达式中使用主题变量(来自"for")



我有这样的代码,它可以按预期工作:

my @words = 'foo', 'bar';
my $text = 'barfoo';
for @words -> $to-regex {
$text ~~ m/ ($to-regex) {say "matched $0"}/;
}

它打印:

matched foo
matched bar

但是,如果我尝试在for循环中使用主题变量,如:

for @words { # implicit "-> $_", AFAIK
$text ~~ m/ ($_) {say "matched $0"}/;
}

我得到这个:

matched barfoo
matched barfoo

使用后缀的相同结果:

$text ~~ m/ ($_) {say "matched $0"}/ for @words; # implicit "-> $_", AFAIK

这是正则表达式中主题变量的特殊情况吗?

它应该容纳与其匹配的整个字符串吗?

智能匹配操作员有三个阶段的

  1. 将左参数临时别名为$_
  2. 运行右边的表达式
  3. 根据该结果调用.ACCEPTS($_)

所以这不是正则表达式的特殊情况,而是~~的工作方式。

for 1,2,3 {
$_.print;
'abc' ~~ $_.say
}
# 1abc
# 2abc
# 3abc

最新更新