On the other hand, using the keys function allows sorting of hash elements.
#!/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)
#!/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).