What scope does ":my $foo" have and what is it used for?

Viewed 137

With a regex, token or rule, its possible to define a variable like so;

token directive {
    :my $foo = "in command";
    <command> <subject> <value>?
}

There is nothing about it in the language documentation here, and very little in S05 - Regexes and Rules, to quote;

Any grammar regex is really just a kind of method, and you may declare variables in such a routine using a colon followed by any scope declarator parsed by the Perl 6 grammar, including my, our, state, and constant. (As quasi declarators, temp and let are also recognized.) A single statement (up through a terminating semicolon or line-final closing brace) is parsed as normal Perl 6 code:

token prove-nondeterministic-parsing {
    :my $threshold = rand;
    'maybe' \s+ <it($threshold)>
}

I get that regexen within grammars are very similar to methods in classes; I get that you can start a block anywhere within a rule and if parsing successfully gets to that point, the block will be executed - but I don't understand what on earth this thing is for.

Can someone clearly define what it's scope is; explain what need it fulfills and give the typical use case?

1 Answers
Related