@@ -567,6 +567,42 @@ Here's the final code:
567
567
}
568
568
= end code
569
569
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 fparam aend 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
+
570
606
Hopefully this has helped introduce you to the grammars in Perl 6 and shown you
571
607
how grammars and grammar action classes work together. For more information,
572
608
check out the more advanced L < Perl Grammar
0 commit comments