How to sort hash by value in perl.

#!/usr/bin/perl -w
sub Ascending { $grades{$a} cmp $grades{$b}; }
sub Descending { $grades{$b} cmp $grades{$a}; }
%grades = (
student1 => 90,
student2 => 75,
student3 => 96,
student4 => 55,
student5 => 76,
);

foreach $key (sort Descending (keys(%grades))) {
print "$key : $grades{$key}\n";
}

// Using the Ascending subroutine will print the values in ascending order.
 

Search Topics

Popular Posts