Using actions
Grammars by themselves do not just parse the source text and extract data pieces from it. To make the program execute the code, actions are needed. Actions in grammars are pieces of Perl 6 code that are triggered when the grammar successfully parses a rule or a token.
Let us take a look at the variable-declaration
rule:
rule variable-declaration { 'my' <variable> }
When the grammar finds the sequence my $x
in the source text, the rule is satisfied. At this point, you may add an action:
rule variable-declaration { 'my' <variable> {say 'Declaring a variable'} }
An action can be a simple alert like this but it also may be much more complex code that will be executed as a reaction to the variable declaration.
To make the action act properly, it needs to know the type of the variable (whether it contains the $
or the @
sigil) and its name. Actions have access to Match objects reflecting the current state of the parsed fragment. Named subrules can be found in the Match...