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

True

Comments

  1. Because TOP is a rule, the spaces in the pattern allow whitespace around the = in the input.

  2. So 'x = 5' parses. With a token for TOP, only 'x=5' would match.

Course navigation

A spaced assignment   |   Grammars, classes, and inheritance