如何从 Perl 哈希表中获取最小值的键

3
我有一个脚本,可以从哈希值中选择最小值。
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:$min\n";

在哈希值中,我能够得到50作为所有值中的最小值。但是,如何获取对应于最小值的哈希键,即1596561300

2个回答

5

从键中,你可以得到值。因此,你想要具有最小关联值的键。

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};
   }
}

2

查看@ikegami的答案,这是最干净、最快速的解决方案,能够确切地回答提问者的问题。
如果你需要按照数值大小排序访问其他键(我从你的示例中推断出这是你想要的),请使用以下代码:

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]

或按值字母表顺序排序:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接