我已经在网上浏览了很多解决方案,但我找不到满足我需求的东西。
我有一个很大的单词列表,每个单词附加了值
示例:
my %list = (
word => 10,
xword => 15,
yword => 1
)
列表一直在继续,但我希望能够返回具有最高对应值的前5个哈希元素
答案 0 :(得分:2)
use strict;
use warnings;
sub topN {
my ($N, %list) = (shift, @_);
$N = keys %list if $N > keys %list;
return (sort { $list{$b} <=> $list{$a} } keys %list)[0..$N-1];
}
my %list = ( word => 10, xword => 15, yword => 1, zword => 4);
print join (",", topN(5, %list)), "\n";
输出:
xword,word,zword,yword
答案 1 :(得分:1)
这可以满足您的需求。请注意,如果您的哈希值少于五个元素,它将抛出Use of uninitialized value
警告,您可能需要添加代码以满足该要求。它的效率也很低,因为它对整个哈希进行排序,而不是仅查找前五个值。这是否是一个问题取决于您的情况。
use strict;
use warnings;
my %list = (
word => 10,
xword => 15,
yword => 1,
);
my @top5 = (sort { $list{$b} <=> $list{$a} } keys %list)[0..4];
print "$_\n" for @top5;
<强>输出强>
xword
word
yword
答案 2 :(得分:0)
use strict;
use warnings;
my %list = (
word => 10,
xword => 15,
yword => 1,
);
my @top5 = sort { $list{$b} <=> $list{$a} } keys %list;
splice(@top5, 5) if @top5 > 5;
print "$_\n" for @top5;