Hypothetical Variables
Hypothetical variables are a
powerful way of building up data structures from within a match.
Ordinary captures with ( )
store the result of the
captures in $1
, $2
, etc. The
values stored in these variables will be kept if the match is
successful, but thrown away if the match fails (hence the term
“hypothetical”). The numbered
capture
variables are accessible
outside the match, but only within the immediate surrounding lexical
scope:
"Zaphod Beeblebrox" ~~ m:w/ (\w+) (\w+) /; print $1; # prints Zaphod
You can also capture into any user-defined variable with the binding
operator :=
. These variables must already be
defined in the lexical scope surrounding the rule:
my $person; "Zaphod's just this guy." ~~ / ^ $person := (\w+) /; print $person; # prints Zaphod
Repeated matches can be captured into an array:
my @words; "feefifofum" ~~ / @words := (f<-[f]>+)* /; # @words contains ("fee", "fi", "fo", "fum")
Pairs of repeated matches can be captured into a hash:
my %customers; $records ~~ m:w/ %customers := [ <id> = <name> \n]* /;
If you don’t need the captured value outside the
rule, use a $?
variable instead. These are only
directly accessible within the rule:
"Zaphod saw Zaphod" ~~ m:w/ $?name := (\w+) \w+ $?name/;
A match of a named rule stores the result in a $?
variable with the same name as the rule. These variables are also
accessible only within the rule:
"Zaphod saw Zaphod" ~~ m:w/ <name> \w+ $?name /;
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.