#!/usr/bin/perl -w
#----------------------------------------------------------------------#
# printHashByValue.pl #
#----------------------------------------------------------------------#
#----------------------------------------------------------------------#
# FUNCTION: hashValueAscendingNum #
# #
# PURPOSE: Help sort a hash by the hash 'value', not the 'key'. #
# Values are returned in ascending numeric order (lowest #
# to highest). #
#Sorting numbers sort的用法
#The problem with sort's default behaviour is that it sorts alphabetically. Here's snippet that incorrectly sorts numbers:
#my @numbers = (20,1,10,2);
#my @incorrectly_sorted_numbers=sort @numbers;
#print "\n\nNumbers, incorrectly sorted\n";
#print join "\n",@incorrectly_sorted_numbers;
#Here's the output of this Perl script. Probably not what was intended.
#1
#10
#2
#20
#If you want to have the numbers sorted by their value, you need use the <=> (aka Spaceship Operator):
#my @numbers = (20,1,10,2);
#my @correctly_sorted_numbers = sort {$a <=> $b} @numbers;
#print "\n\nNumbers, correctly sorted\n";
#print join "\n",@correctly_sorted_numbers;
#The variables $a and $b are automatically set by Perl. The output is now:
#1
#2
#10
#----------------------------------------------------------------------#
sub hashValueAscendingNum {
$grades{$a} <=> $grades{$b};
}
#----------------------------------------------------------------------#
# FUNCTION: hashValueDescendingNum #
# #
# PURPOSE: 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 "\nGRADES IN ASCENDING NUMERIC ORDER:\n";
foreach $key (sort hashValueAscendingNum (keys(%grades))) {
print "\t$grades{$key} \t\t $key\n";
}
print "\nGRADES IN DESCENDING NUMERIC ORDER:\n";
foreach $key (sort hashValueDescendingNum (keys(%grades))) {
print "\t$grades{$key} \t\t $key\n";
}
阅读(2409) | 评论(1) | 转发(0) |