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/local/bin/perl
use strict;
use warnings;

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

my (%prices, $max_price, $most_exp);

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

$max_price = 0;
$most_exp = "";

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

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

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

Example 2 - using the keys function

#!/usr/local/bin/perl
use strict;
use warnings;

#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 the price).


Table of Contents.