Why does this perl 6 grammar not work?

I don’t know perl 5, but I thought I would have a game with perl 6. I try my grammar capabilities, but still have no luck. Here my code is far:

grammar CopybookGrammar { token TOP { {say "at TOP" } <aword><num>} token aword { {say "at word" } [a..z]+ } token num { {say "at NUM" } [0..9]+ } } sub scanit($contents) { my $match1 = CopybookGrammar.parse($contents); say $match1; } scanit "outline1"; 

The output is as follows:

 at TOP at word (Any) 

For some reason, it does not comply with the <num> rule. Any ideas?

+5
source share
1 answer

You forgot the angle brackets in the character classes :

[a..z]+ must be <[a..z]>+

[0..9]+ must be <[0..9]>+

By itself, the square brackets [ ] simply act as a group that is not exciting in Perl 6 regexes. Thus, [a..z]+ will correspond to the letter "a", followed by any two characters, followed by the letter "z", and then all this again any number of times. Since this does not match the word "outline", the <aword> token did not match you, and the parsing did not continue with the <num> token.


PS: When debugging grammars, a more convenient alternative to adding blocks {say ...} is to use Grammar :: Debugger . After installing this module, you can temporarily add the line use Grammar::Debugger; into your code and run your program - then it will go through your grammar step by step (using the ENTER key to continue) and tell you which tokens / rules match along the way.

+8
source

Source: https://habr.com/ru/post/1261214/


All Articles