Skip navigation.
Home
Your source for Perl tips, howto's, faq and tutorials
( categories: )

The idea is to sort the list of keys of the hash and iterate through the sorted list using a 'foreach' statement.

-- order by key alphabetically

foreach my $key ( sort keys %hash )
{
  print "key: " . $key . " value: " . $hash{$key} . "\n";
}

-- order by key numerically

foreach my $key ( sort { $a <=> $b } keys %hash )
{
  print "key: " . $key . " value: " . $hash{$key} . "\n";
}

-- order by value alphabetically

foreach my $key ( sort { $hash{$a} cmp $hash{$b} } keys %hash )
{
  print "key: " . $key . " value: " . $hash{$key} . "\n";
}

-- order by value numerically

foreach my $key ( sort { $hash{$a} <=> $hash{$b} } keys %hash )
{
  print "key: " . $key . " value: " . $hash{$key} . "\n";
}