perl6/doc/lib/Hash
doc src
In an expression like 1 + 2 * 3 , the 2 * 3 is evaluated first
because the infix * has tighter B<precedence> than the + .
The following table summarizes the precedence levels in Perl 6, from
tightest to loosest:
(title) class Hash
class Hash is EnumMap { }
A Hash is a mutable mapping from keys to values (called I<dictionary>,
I<hash table> or I<map> in other programming languages). The values are
all scalar containers, which means you can assign to them.
Hashes are usually stored in variables with the percent % sigil.
Hash elements are accessed by key via the { } postcircumfix operator:
my $home = %*ENV{'HOME'};
For literal string keys without whitespace, < > can be used instead:
my $home = %*ENV<HOME>;
You can add new pairs simply by assigning to an unused key:
my %h;
%h{'new key'} = 'new value';
Hash assignment
Assigning a list of elements to a hash variable first empties the variable,
and then iterates the elements of the right-hand side. If an element is an
L<Enum> (or a subclass like L<Pair>), its key is taken as a new hash key,
and its value as the new hash value for that key. Otherwise the value
is coereced to L<Str> and used as a hash key, while the next element of the
list is taken as the corresponding value.
my %h = 'a', 'b', c => 'd', 'e', 'f';
# same as
my %h = a => 'b', c => 'd', e => 'f';
# or
my %h = <a b c d e f>;
If an L<Enum> is encountered where a value is expected, it is used as a
hash value:
my %h = 'a', 'b' => 'c';
say %h<a>.WHAT; # Pair();
say %h<a>.key; # b
If the same key appears more than once, the value associated with its last
occurence is stored in the hash:
my %h = a => 1, a => 2;
say %h<a>; # 2
Methods
(head2) push
multi method push(Hash:D: *@new)
Adds the @new elements to the hash with the same semantics as hash
assignment, but with three exceptions:
(item) the hash isn't emptied first, ie old pairs are not deleted.
(item) if a key already exists in the hash, and the corresponding value is an
L<Array>, the new value is pushed onto the array (instead of replacing it).
(item) if a key already exists in the hash, and the corresponding value is not
an L<Array>, old and new value are both placed into an array in the place
of the old value.