5.9. Sorting a HashProblemYou need to work with the elements of a hash in a particular order. SolutionUse # %HASH is the hash to sort
@keys = sort { criterion() } (keys %hash);
foreach $key (@keys) {
$value = $hash{$key};
# do something with $key, $value
}DiscussionEven though you can't directly maintain a hash in a specific order (unless you use the Tie::IxHash module mentioned in Recipe 5.6), you can access its entries in any order. This technique offers many variations on the same basic mechanism: You extract the keys, reorder them using the The following code simply uses foreach $food (sort keys %food_color) {
print "$food is $food_color{$food}.\n";
}This sorts the keys by their associated values: foreach $food (sort { $food_color{$a} cmp $food_color{$b} }
keys %food_color)
{
print "$food is $food_color{$food}.\n";
}This sorts by length of the values: @foods = sort { length($food_color{$a}) <=> length($food_color{$b}) }
keys %food_color;
foreach $food (@foods) {
print "$food is $food_color{$food}.\n";
}See AlsoThe |