Search code examples
perlhashminimum

How to get minimum values key from hash in Perl


I have script which is able to pick minimum value from hash values.

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

Here I am able to get 50 as a minimum value out of all the values in hash values. But how would I also get the hash key that corresponds to the minimum value, i.e.,1596561300.


Solution

  • From the key, you can get the value. So you want the key with the minimal associated value.

    min LIST can be written as reduce { $a <= $b ? $a : $b } LIST, so we can use

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

    or

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