Skip to content

Commit 7f0c910

Browse files
committed
start to document Hash
1 parent b45ecfe commit 7f0c910

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

lib/Hash.pod

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
=begin pod
2+
3+
=TITLE class Hash
4+
5+
class Hash is EnumMap { }
6+
7+
A Hash is a mutable mapping from keys to values (called I<dictionary>,
8+
I<hash table> or I<map> in other programming languages). The values are
9+
all scalar containers, which means you can assign to them.
10+
11+
Hashes are usually stored in variables with the percent C<%> sigil.
12+
13+
Hash elements are accessed by key via the C<{ }> postcircumfix operator:
14+
15+
my $home = %*ENV{'HOME'};
16+
17+
For literal string keys without whitespace, C<< < > >> can be used instead:
18+
19+
my $home = %*ENV<HOME>;
20+
21+
You can add new pairs simply by assigning to such an element access:
22+
23+
my %h;
24+
%h{'new key'} = 'new value';
25+
26+
=head1 Hash assignment
27+
28+
Assigning a list of elements to a hash variable first empties the variable,
29+
and then iterates the elements of right-hand side. If an element is an
30+
L<Enum> (or of a subclass like L<Pair>), its key is taken as a new hash key,
31+
and its value as the new hash value for that key. Otherwise the value
32+
is coereced to L<Str> and used as a hash key, while the next element of the
33+
list is taken as the corresponding value.
34+
35+
my %h = 'a', 'b', c => 'd', 'e', 'f';
36+
# same as
37+
my %h = a => 'b', c => 'd', e => 'f';
38+
# or
39+
my %h = <a b c d e f>;
40+
41+
If an L<Enum> is enocuntered where a value is expected, it is used as a
42+
hash value:
43+
44+
my %h = 'a', 'b' => 'c';
45+
say %h<a>.WHAT; # Pair();
46+
say %h<a>.key; # b
47+
48+
If the same key appears more than once, the value associated with its last
49+
occurence is stored in the hash:
50+
51+
my %h = a => 1, a => 2;
52+
say %h<a>; # 2
53+
54+
=head1 Methods
55+
56+
=head2 push
57+
58+
multi method push(Hash:D: *@new)
59+
60+
Adds the C<@new> elements to the hash with the same semantics as hash
61+
assignment, but with three exceptions:
62+
63+
=item the hash isn't emptied first, ie old pairs are not deleted
64+
65+
=item if a key already exists in the hash, and the corresponding value is an
66+
L<Array>, the new value is pushed onto the arary (instead of replacing it).
67+
68+
=item if a key already exists in the hash, and the corresponding value is not
69+
an L<Array>, old and new value are both placed into an array in the place
70+
of the old value.
71+
72+
=end pod

0 commit comments

Comments
 (0)