O'Reilly logo

Perl 6 and Parrot Essentials, Second Edition by Leopold Tötsch, Dan Sugalski, Allison Randal

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required