If you interpolate a regex, it is a sub regex.
If you have something like a sigil, then the match data structure gets
thrown away.
You can put it back in as a named
> $input ~~ / <pattern=$pattern>
「9 million」
pattern => 「9 million」
0 => 「9」
1 => 「million」
Or as a numbered:
> $input ~~ / $0 = <$pattern>
「9 million」
0 => 「9 million」
0 => 「9」
1 => 「million」
Or put it in as a lexical regex
> my regex pattern { (\d+) \s+ (\w+) }
> $input ~~ / <pattern> /
「9 million」
pattern => 「9 million」
0 => 「9」
1 => 「million」
Or just use it as the whole regex
> $input ~~ $pattern # variable
「9 million」
0 => 「9」
1 => 「million」
> $input ~~ &pattern # my regex pattern /…/
「9 million」
0 => 「9」
1 => 「million」
On Thu, Mar 11, 2021 at 2:29 AM Joseph Brenner <[email protected]> wrote:
> Does this behavior make sense to anyone? When you've got a regex
> with captures in it, the captures don't work if the regex is
> stashed in a variable and then interpolated into a regex.
>
> Do capture groups need to be defined at the top level where the
> regex is used?
>
> { # From a code example in the "Parsing" book by Moritz Lenz, p. 48,
> section 5.2
> my $input = 'There are 9 million bicycles in beijing.';
> if $input ~~ / (\d+) \s+ (\w+) / {
> say $0.^name; # Match
> say $0; # 「9」
> say $1.^name; # Match
> say $1; # 「million」
> say $/;
> # 「9 million」
> # 0 => 「9」
> # 1 => 「million」
> }
> }
>
> say '---';
>
> { # Moving the pattern to var which we interpolate into match
> my $input = 'There are 9 million bicycles in beijing.';
> my $pattern = rx{ (\d+) \s+ (\w+) };
> if $input ~~ / <$pattern> / {
> say $0.^name; # Nil
> say $0; # Nil
> say $1.^name; # Nil
> say $1; # Nil
> say $/; # 「9 million」
> }
> }
>
> In the second case, the match clearly works, but it behaves as
> though the capture groups aren't there.
>
>
> raku --version
>
> Welcome to 𝐑𝐚𝐤𝐮𝐝𝐨™ v2020.10.
> Implementing the 𝐑𝐚𝐤𝐮™ programming language v6.d.
>