Skip to content


Subversion checkout URL

You can clone with
Download ZIP
Fetching contributors…

Cannot retrieve contributors at this time

73 lines (47 sloc) 2.09 KB
=begin pod
=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 C<%> sigil.
Hash elements are accessed by key via the C<{ }> postcircumfix operator:
my $home = %*ENV{'HOME'};
For literal string keys without whitespace, C< < > > 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';
=head1 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
=head1 Methods
=head2 push
multi method push(Hash:D: *@new)
Adds the C<@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.
=end pod
Jump to Line
Something went wrong with that request. Please try again.