Course of Raku / Regexes and grammars / Grammars / Grammars, classes, and inheritance / Exercises / A number with proto
Solution: A number with proto
Here is a possible solution to the task.
Code
grammar Number {
token TOP { <number> }
proto token number {*}
token number:sym<dec> { \d+ }
token number:sym<hex> { '0x' <[0..9a..f]>+ }
}
say Number.parse('0xff').defined;🦋 You can find the source code in the file proto-number.raku.
Output
TrueComments
The proto token
numberhas two variants,decandhex.For
0xff, thedecvariant matches only the leading0, which would leavexffover; thehexvariant matches the whole thing. Longest-token matching therefore pickshex, and the string parses. The same grammar still accepts a plain decimal such as42.