Chapter 17. Grammars
Grammars are patterns on a higher plane of existence. They integrate and reuse pattern fragments to parse and react to complicated formats. This feature is at the core of Perl 6 in a very literal sense; the language itself is implemented as a grammar. Once you start using it you’ll probably prefer it to regexes for all but the most simple problems.
A Simple Grammar
A grammar is a special sort of package. It can have methods and subroutines but
mostly comprises special pattern methods called regex
, token
,
and rule
. Each of these define a
pattern and apply different modifiers.
Note
Perl 6 tends to refer to regex
,
token
, and rule
declarations as “rules,” which can be a
bit imprecise at times. In this book, you can tell the difference
between the language keyword and the general term by the typesetting.
I’ll try to not present an ambiguous situation.
Start with something simple (too simple for grammars). Define a
TOP
pattern that matches digits as the
starting point. That name is special because .parse
uses it by
default. In this example, you declare that with regex
:
grammar Number { regex TOP { \d } } my $result = Number.parse( '7' ); # works put $result ?? 'Parsed!' !! 'Failed!'; # Parsed!
This succeeds. .parse
applies the
grammar to the entire value of 7
. It
starts with the parts that TOP
describes. It can match a digit, and the value you pass to .parse
is a digit.
When .parse
succeeds, it returns
a Match
object (it returns Nil
when it fails). Try it with a different ...
Get Learning Perl 6 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.