Hashes

Iterating over all hash elements: When should I use the keys and when the each function?

Iteration over all hash elements using the each function is more efficient than with the keys function.

On the other hand, using the keys function allows sorting of hash elements.

Example 1 - using the each function

#!/usr/bin/perl

# calculate maximum price, using the each function
# print the most expensive clothes



%prices = ("shirt"    => 45,
           "pullover" => 90,
           "trousers" => 120,
           "socks"    => 15);

$max_price = 0;
$most_exp_item = "";

while (my ($key, $value) = each (%prices)) {

   if ($value > $max_price) {
      $max_price = $value;
      $most_exp_item = $key;
   }
}

print "Most expensive clothes: $most_exp_item ($max_price NIS)\n";
Result:
Most expensive clothes: trousers (120 NIS)

Example 2 - using the keys function

#!/usr/bin/perl


#print clothes in alphabetical order (and their prices)

my %prices = ("shirt"    => 45,
              "pullover" => 90,
              "trousers" => 120,
              "socks"    => 15);

my $key;
foreach $key (sort keys %prices) {
   print "$key: $prices{$key}\n";
}
Result:
pullover: 90
shirt: 45
socks: 15
trousers: 120

Note: We will learn later how to sort a hash by value (i.e. by price).


Table of Contents.
Previous.