Course of Raku / Regexes and grammars / Grammars / The parse tree, make and made / Exercises / Extract the number
Solution: Extract the number
Here is a possible solution to the task.
Code
grammar Weight {
token TOP { <number> 'kg' { make $<number>.Int } }
token number { \d+ }
}
say Weight.parse('5kg').made;🦋 You can find the source code in the file extract-the-number.raku.
Output
5Comments
The pattern matches the digits and the literal
kg, but the inline block stores only$<number>.Int— the integer, without the unit.madereads that value back: a real5, ready to compute with, rather than the text5kg. This is the typical job ofmake— turning a match into the clean value you actually want.