Skip to content

Commit 02b3c73

Browse files
authored
Merge pull request #1635 from perl6/W4anD0eR96-patch-1
Add example "Add actions directly", review needed
2 parents c091ada + aac1952 commit 02b3c73

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

doc/Language/grammar_tutorial.pod6

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -567,6 +567,42 @@ Here's the final code:
567567
}
568568
=end code
569569
570+
=head2 Add actions directly
571+
572+
Above we see how to associate grammars with action objects and perform
573+
actions on the match object. However, when we want to deal with the match
574+
object, that isn't the only way. See the example below:
575+
576+
=begin code
577+
grammar G {
578+
rule TOP { <function-define> }
579+
rule function-define {
580+
'sub' <identifier>
581+
{
582+
say "func " ~ $<identifier>.made;
583+
make $<identifier>.made;
584+
}
585+
'(' <parameter> ')' '{' '}'
586+
{ say "end " ~ $/.made; }
587+
}
588+
token identifier { \w+ { make ~$/; } }
589+
token parameter { \w+ { say "param " ~ $/; } }
590+
}
591+
592+
G.parse('sub f ( a ) { }');
593+
# OUTPUT: «func f␤param a␤end f␤»
594+
=end code
595+
596+
This example is a reduced portion of a parser. Let's focus more on the feature
597+
it shows.
598+
599+
First, we can add actions inside the grammar itself, and such actions are
600+
performed once the control flow of the regex arrives at them. Note that action
601+
object's method will always be performed after the whole regex item matched.
602+
Second, it shows what C<make> really does, which is no more than a sugar of
603+
C<$/.made = ...>. And this trick introduces a way how we pass messages within
604+
a regex item.
605+
570606
Hopefully this has helped introduce you to the grammars in Perl 6 and shown you
571607
how grammars and grammar action classes work together. For more information,
572608
check out the more advanced L<Perl Grammar

0 commit comments

Comments
 (0)