Course of Raku / Regexes and grammars / Grammars / Tokens and rules / Exercises / A spaced assignment
Solution: A spaced assignment
Here is a possible solution to the task.
Code
grammar Assign {
rule TOP { <key> '=' <value> }
token key { \w+ }
token value { \w+ }
}
say Assign.parse('x = 5').defined;🦋 You can find the source code in the file spaced-assignment.raku.
Output
TrueComments
Because
TOPis arule, the spaces in the pattern allow whitespace around the=in the input.So
'x = 5'parses. With atokenforTOP, only'x=5'would match.
The whitespace a rule allows is
optional, not required: the significant space matches
zero spaces just as happily as one, so the unspaced form parses
too:
say Assign.parse('x=5').defined; # TrueThe rule therefore accepts 'x = 5',
'x=5', and even 'x =5' alike — flexibility
without spelling out where a space may or may not go.
Course navigation
← A spaced assignment | Grammars, classes, and inheritance →