Sort a hash based on the string length of the values

Hi,

I want to be able to sort/print a hash based on the string length of the values.

For example

 %hash = (
        key1 => 'jeri',
        key2 => 'corona',
        key3 => 'una,
    );

I want to be able to print in the following order (smallest to largest)
una,jeri,corona

OR vice versa (I don't have a preference as to which)
corona,jeri,una

How can I do this with out looping through the hash many many times?

Thanks,
Jeri

try:

#!/usr/bin/perl
 
%hash = (
key1 => "jeri",
key2 => "corona",
key3 => "una"
);
 
print "\nforward sort...\n\n";
 
foreach $key (sort {length($hash{$a}) cmp length($hash{$b})} keys %hash) {
   print "$hash{$key} $key " . length($hash{$key}) . "\n";
}
 
print "\nreverse sort...\n\n";
 
foreach $key (reverse sort {length($hash{$a}) cmp length($hash{$b})} keys %hash) {
   print "$hash{$key} $key " . length($hash{$key}) . "\n";
}
1 Like