Chapter 9. Associatives
An Associative
indexes to a value with an arbitrary name called the key. Associative
s are unordered
because the keys have no relative order. Other languages have similar data
types they call associative arrays, dictionaries, hashes, maps, or something
similar that do the same thing. There are several types of specialized
associative data structures, and you’ve already been using some of
them.
Pairs
A Pair
has a single key and a value. You’ve already used these in their
adverbial form, although you didn’t know they were Pair
s. Create a Pair
through general object construction
with the name and value as arguments:
my $pair = Pair.new: 'Genus', 'Hamadryas';
The =>
is the Pair
constructor. You don’t have to
quote the lefthand side because the =>
does that for you as long as it looks like
a term:
my $pair = Genus => 'Hamadryas'; # this works my $nope = ⛇ => 'Hamadryas'; # this doesn't
Any value can be a Pair
value. Here’s a value that’s a
List
:
my $pair = Pair.new: 'Colors', <blue black grey>;
Combining .new
and =>
probably doesn’t do what you want. Passing
it a single Pair
means that you are missing its
value. The .new
method thinks that the Pair
is the key and you forgot the
value:
my $pair = Pair.new: 'Genus' => 'Hamadryas'; # WRONG!
Adverbs
A more common syntax is the adverbial form that you have already
seen with Q
quoting. Start
with a colon, add the unquoted name, and specify the value inside <>
for allomorphic quoting or inside ()
where you quote the value yourself: ...
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.