I don't know perl 5, but I thought I'd have a play with perl 6. I am trying out its grammar capabilities, but so far I'm having no luck. Here's my code 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 appear to matching the <num>
rule. Any ideas?
You forgot the angled brackets in the character classes syntax:
[a..z]+
should be <[a..z]>+
[0..9]+
should be <[0..9]>+
By themselves, square brackets [ ]
simply act as a non-capturing group in Perl 6 regexes. So [a..z]+
would match the letter "a", followed by any two characters, followed by the letter "z", and then the whole thing again any number of times. Since this does not match the word "outline", the <aword>
token failed to match for you, and parsing did not continue to the <num>
token.
PS: When debugging grammars, a more convenient alternative to adding {say ...}
blocks everywhere, is to use Grammar::Debugger. After installing that module, you can temporarily add the line use Grammar::Debugger;
to your code, and run your program - then it'll go through your grammar step by step (using the ENTER key to continue), and tell you which tokens/rules match along the way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With