5

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?

Julio
  • 5,208
  • 1
  • 13
  • 42
  • Note that regexes in raku are dreadfully slow and if you can avoid them you should. Here for instance, if one is just looking for presence of a substr in a str, using the index method is worth considering. – Holli Oct 17 '20 at 12:11

1 Answers1

8

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
Brad Gilbert
  • 33,846
  • 11
  • 78
  • 129