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

这是正则表达式中topic变量的特例吗?

是否应该保留与之匹配的整个字符串?

解决方法

智能匹配运算符分为三个阶段

  1. 将左参数暂时别名为$_
  2. 在右侧运行表达式
  3. 对该结果致电.ACCEPTS($_)

因此,对于正则表达式而言,这不是特殊情况,而是~~始终有效的方式。

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...