Question - How do I sort a hash by the hash value?
Answer -
Here's a program that prints the contents
of the grades hash, sorted numerically by the hash value:
#!/usr/bin/perl -w
# Help sort a hash by the hash 'value', not the 'key'.
to highest).
sub hashValueAscendingNum {
$grades{$a} <=> $grades{$b};
}
# Help sort a hash by the hash 'value', not the 'key'.
# Values are returned in descending numeric order
# (highest to lowest).
sub hashValueDescendingNum {
$grades{$b} <=> $grades{$a};
}
%grades = (
student1 => 90,
student2 => 75,
student3 => 96,
student4 => 55,
student5 => 76,
);
print "\n\tGRADES IN ASCENDING NUMERIC ORDER:\n";
foreach $key (sort hashValueAscendingNum (keys(%grades))) {
print "\t\t$grades{$key} \t\t $key\n";
}
print "\n\tGRADES IN DESCENDING NUMERIC ORDER:\n";
foreach $key (sort hashValueDescendingNum (keys(%grades))) {
print "\t\t$grades{$key} \t\t $key\n";
}
type?
Yes. Perl can make a scalar or hash type reference by using backslash operator.
For example
$str = "here we go"; # a scalar variable
$strref = \$str; # a reference to a scalar
@array = (1..10); # an array
$arrayref = \@array; # a reference to an array
Note that the reference itself is a scalar.