Skip to Content
Learning Perl 6
book

Learning Perl 6

by brian d foy
September 2018
Beginner
474 pages
9h 35m
English
O'Reilly Media, Inc.
Content preview from Learning Perl 6

Chapter 9. Associatives

An Associative indexes to a value with an arbitrary name called the key. Associatives 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 Pairs. 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: ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Think Perl 6

Think Perl 6

Laurent Rosenfeld, Allen B. Downey
Perl 6 Deep Dive

Perl 6 Deep Dive

Andrew Shitov
Perl by Example

Perl by Example

Ellie Quigley

Publisher Resources

ISBN: 9781491977675Errata Page