7.6 Hypothetical Variables

     

7.6 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 ; # 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 /; 



Perl 6 and Parrot Essentials
Perl 6 and Parrot Essentials, Second Edition
ISBN: 059600737X
EAN: 2147483647
Year: 2003
Pages: 116

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net