Chapter 7. Grammars and Rules
Perl 6 “regular expressions” are so far beyond the formal definition of regular expressions that we decided it was time for a more meaningful name.[17] We now call them “rules.” Perl 6 rules bring the full power of recursive descent parsing to the core of Perl, but are comfortably useful even if you don’t know anything about recursive descent parsing. In the usual case, all you’ll ever need to know is that rules are patterns for matching text.
Using Rules
Rules are a language within a language, with their own syntax and conventions. At the highest level, though, they’re just another set of Perl constructs. So the first thing to learn about rules is the Perl “glue” code for creating and using them.
Immediate Matches
The simplest way to create and
use a rule is an immediate match. A rule
defined with the m//
operator always immediately matches.
Substitutions, defined with the
s///
operator also immediately
match. A rule defined with the //
operator
immediately matches when it’s in void, Boolean,
string, or numeric context, or the argument of the
smart-match operator
(~~
).
if ($string ~~ m/\w+/) { . . . } if ($string ~~ s/\w+/word/) { . . . } if ($string ~~ /\w+/) { . . . }
You can substitute other delimiters, such as # . . . #
, [ . . . ]
, and { . . . }
, for the standard / . . . /
, though
? . . . ?
and ( . . . )
are not
valid delimiters:
if ($string ~~ s[\w+][word]) { . . . }
Deferred Matches
Sometimes you want a little more flexibility than an immediate ...
Get Perl 6 and Parrot Essentials, Second Edition 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.