如何使用哈希在Perl中获取基于VALUE的KEY? 如果我有:
"dime"=>"4"
"nickle"=>"5"
"quarter"=>"2"
"dollar"=>"6"
现在我对它们进行排序,最高的是6.我希望能够获得“美元”。这是我试过的:
# sort money based on count
my @sorted = sort {$deposit->{$b} cmp $deposit->{$a}} keys %$deposit;
my %rhash;
@rhash{values %deposit} = keys %deposit;
$owner = $rhash->{$sorted[0]}; #get highest count
答案 0 :(得分:3)
如果您的值是唯一的,则可以反转地图:
my %rev = map { $deposit->{$_} => $_ } keys %$deposit;
[假设$deposit
是对列出的哈希的引用]
答案 1 :(得分:2)
排序是O(n log n),这比需要的更多。找到最高可以使用O(n)算法完成。以下是使用“高水位线”算法的例子:
#!/usr/bin/perl
use warnings;
use strict;
my %deposit = (
"dime"=>"4",
"nickle"=>"5",
"quarter"=>"2",
"dollar"=>"6",
);
my $hi_key;
foreach (keys %deposit) {
$hi_key = $_ if $deposit{$_} > $deposit{$hi_key};
}
print "high is: $hi_key => $deposit{$hi_key}\n";