Scripting >> Perl >> How to sort a hash by its values


To sort by ascending values:-
 
foreach $key (sort { $hash{$a} <=> $hash{$b} } keys %hash) {
        print "$hash{$key} , $key\n";
    }
 
To sort by descending values:-
 
foreach $key (sort { $hash{$b} <=> $hash{$a} } keys %hash) {
        print "$hash{$key} , $key\n";
    }