3

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.

Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
vkk05
  • 3,137
  • 11
  • 25

2 Answers2

5

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};
   }
}
ikegami
  • 367,544
  • 15
  • 269
  • 518
2

See the answer by @ikegami for the cleanest, fastest solution to the exact question of the OP.
If you need to access other keys in the order sorted by values numerically (I assume from your example that this is what you want), use this:

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]

Or sorted by values ASCIIbetically:

my @keys_sorted_by_value = sort { $hash{$a} cmp $hash{$b} } keys %hash;
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47