如何在Perl中从散列中获取最小值密钥



我有一个脚本,可以从哈希值中选择最小值。

use strict;
use warnings;
use Data::Dumper;
use List::Util qw(min);
my @array = qw/50 51 52 53 54/;
my $time = 1596561300;
my %hash;
foreach my $element(@array){  
$hash{$time} = $element;
$time += 6; #based on some condition incrementing the time to 6s
}
print Dumper(%hash);
my $min = min values %hash; 
print "min:$minn";

在这里,我能够得到50作为散列值中所有值中的最小值。但是,我如何也获得与最小值相对应的哈希密钥,即1596561300

通过键,您可以获得值。因此,您需要具有最小关联值的密钥。

min LIST可以写成reduce { $a <= $b ? $a : $b } LIST,所以我们可以使用

use List::Util qw( reduce );
my $key = reduce { $hash{$a} <= $hash{$b} ? $a : $b } keys %hash;
my $val = $hash{$key};

my ($key) = keys(%hash);
my $val = $hash{$key};
for (keys(%hash)) {
if ($hash{$_} < $val) {
$key = $_;
$val = $hash{$val};
}
}

请参阅@ikegami的答案,以获得OP确切问题的最干净、最快的解决方案。
如果您需要按数值排序的顺序访问其他键(我从您的示例中假设这就是您想要的(,请使用以下方法:

my @keys_sorted_by_value = sort { $hash{$a} <=> $hash{$b} } keys %hash;
# key with min value: $keys_sorted_by_value[0]
# ...
# key with max value: $keys_sorted_by_value[-1]

或按值排序ASCII按字母顺序:

my @keys_sorted_by_value = sort { $hash{$a} cmp $hash{$b} } keys %hash;

最新更新