Raku: Using topic variable (from a 'for') inside a regex

164 views Asked by At

I have this code that works as expected:

my @words = 'foo', 'bar';
my $text = 'barfoo';

for @words -> $to-regex {
    $text ~~ m/ ($to-regex) {say "matched $0"}/;
}

It prints:

matched foo
matched bar

However, if I try to use topic variable on the for loop, as in:

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

I get this:

matched barfoo
matched barfoo

Same results using postfix for:

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

Is this a special case of the topic variable inside a regex?

Is it supposed to hold the whole string it is matching against?

1

There are 1 answers

0
Brad Gilbert On BEST ANSWER

The smart-match operator has 3 stages

  1. alias the left argument temporarily to $_
  2. run the expression on the right
  3. call .ACCEPTS($_) on that result

So it isn't a special case for a regex, it is how ~~ always works.

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