4

In How can I pass arguments to a Perl 6 grammar? I passed an argument to a rule as part of a submerse. I was wondering how I'd do that completely inside a grammar. Suppose I had something like:

grammar TryIt {
    rule TOP            { \d+ <stuff> }
    rule stuff ($count) { <[ \S A..Z ]>{$count} }
    }

my $match = TryIt.parse: "123 ABCD";
say $match;

How do I pass an argument from TOP to stuff? I didn't find any examples and various guesses about parens near stuff didn't work.

brian d foy
  • 129,424
  • 31
  • 207
  • 592

1 Answers1

4

These forms both work:

<stuff(...)>
<stuff: ...>

Not sure where they're listed in the user documentation, but the S05: Regexes and Rules design document has a section on them.


Note that inside a rule, backreferences like $0 and $/ are only guaranteed to be available after a sequence point, e.g the opening brace of a block. An empty block {} works.

Example:

grammar TryIt {
    token TOP            { (\d+) \s {} <stuff($0)> .* }
    token stuff ($count) { <[ A..Z ]> ** {$count} }
}

say TryIt.subparse: "3 ABCDEFG";

Output:

「3 ABCDEFG」
 0 => 「3」
 stuff => 「ABC」
smls
  • 5,738
  • 24
  • 29