把perl中hash的values按从大到小排列

2024年11月16日 16:11
有1个网友回答
网友(1):

my @keys = sort { $h{$b} <=> $h{$a} } keys %h; #sort the hash table
上面的那一行就是排序的代码。程序如下:

#!/usr/perl/bin
use strict;
use Data::Dumper;
my %h=(
"Alex"=>24,
"Sam"=>25,
"Bob"=>30,
"Andy"=>11,
"Wills"=>35,
"Mary"=>16,
"Helen"=>24
);

print(Dumper(\%h)); # output original hash

my @keys = sort { $h{$b} <=> $h{$a} } keys %h; #sort the hash table
for (@keys){print "$_ -> $h{$_}\n"}

-------------------------------------------
另外,我没记错的话, 可以return一个这样的list:
return ($key, $value)
我倒没用过perl的oo特性,不过我想用class也可以的。