Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Descripe looping over hash keys and values
  • Loading branch information
Paul Cochrane committed Jun 6, 2015
1 parent 118f72b commit 2ed40df
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions lib/Type/Hash.pod
Expand Up @@ -53,6 +53,55 @@ occurrence is stored in the hash:
my %h = a => 1, a => 2;
say %h<a>; # 2
=head1 Looping over hash keys and values
A common idiom for processing the elements in a hash is to loop over the
keys and values, for instance,
my %vowels = 'a' => 1, 'e' => 2, 'i' => 3, 'o' => 4, 'u' => 5;
for %vowels.kv -> $vowel, $index {
"$vowel: $index".say;
}
gives output similar to this:
a: 1
e: 2
o: 4
u: 5
i: 3
where we have used the C<kv> method to extract the keys and their respective
values from the hash, so that we can pass these values into the loop.
Note that the order of the keys and values printed cannot be relied upon;
the elements of a hash are not always stored the same way in memory for
different runs of the same program. Sometimes one wishes to process the
elements sorted on, e.g. the keys of the hash. If one wishes to print the
list of vowels in alphabetical order then one would write
my %vowels = 'a' => 1, 'e' => 2, 'i' => 3, 'o' => 4, 'u' => 5;
for %vowels.sort(*.key)>>.kv -> ($vowel, $index) {
"$vowel: $index".say;
}
which prints
a: 1
e: 2
i: 3
o: 4
u: 5
and is in alphabetical order as desired. To achieve this result, we sorted
the hash of vowels by key (C<%vowels.sort(*.key)>) which we then ask for its
keys and values by applying the C<.kv> method to each element via the unary
C< >> > hyperoperator. The output of this operation is a C<Parcel>, the
items of which need to be passed into the C<for> loop's block as arguments,
hence the need to wrap the key/value pairs in parentheses. Wrapping the
C<for> loop's input in parentheses is not normally necessary when the input
is a C<List>.
=head1 Methods
=head2 method push
Expand Down

0 comments on commit 2ed40df

Please sign in to comment.