Chinaunix首页 | 论坛 | 博客
  • 博客访问: 279233
  • 博文数量: 107
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 74
  • 用 户 组: 普通用户
  • 注册时间: 2016-11-18 09:57
文章分类

全部博文(107)

文章存档

2023年(2)

2021年(1)

2017年(1)

2015年(4)

2014年(9)

2013年(4)

2012年(14)

2011年(49)

2010年(23)

分类:

2010-10-28 18:18:46

#!/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";
}
阅读(2402) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2010-10-29 14:51:53

很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com