user1051414
user1051414

Reputation: 49

In Perl, how can I print the key corresponding to the maximum value in a hash?

How can I print only the first key and element of my hash?

I have already a sorted hash, but I want to print only the first key and respective value thanks,

Thanks to all of you at the end I push the keys and the values to two different @array and print element 0 of each array and it works :)

Upvotes: 0

Views: 3580

Answers (5)

SAN
SAN

Reputation: 2247

In perl hashes there is no ordering for keys. Use sort function to get the keys in the order that you want or you can push the keys into an array as you create the hash and your first key will be in zero th index in the array

You can use the below code, i am assuming hash name is my_hash and keys and values are numbers. If you have strings, you can use cmp instead of <=>. Refer to the sort documentation for more details

Get the max key

foreach (sort {$b <=> $a} keys %my_hash) {
    print "Keys is $_\n";
    print "Value is $my_hash{$_}\n";
    last;
}

Get the key corresponding to the max value

foreach (sort {$my_hash{$b} <=> $my_hash{$a}} keys %my_hash) {
    print "Keys is $_\n";
    print "Value is $my_hash{$_}\n";
    last;
}

Upvotes: 5

Grzegorz Rożniecki
Grzegorz Rożniecki

Reputation: 28015

Just as Alan wrote - hashes don't have specific order, but you can sort hash keys:

foreach my $key (sort keys(%hash)) {
   print $key . ': ' . $hash{$key} . "\n";
}

or, as you wish, get first element from keys array:

my @keys = keys(%hash);
print $keys[0];

Upvotes: 0

Sinan &#220;n&#252;r
Sinan &#220;n&#252;r

Reputation: 118148

For large hashes, if you do not need the sorted keys for any other reason, it might be better to avoid sorting.

#!/usr/bin/env perl

use strict; use warnings;

my %hash = map { $_ => rand(10_000) } 'aa' .. 'zz';

my ($argmax, $max) = each %hash;
keys %hash; # reset iterator

while (my ($k, $v) = each %hash) {
    if ($v >= $max) {
        $max = $v;
        $argmax = $k;
    }
}

print "$argmax => $max\n";

If you are intent on sorting, you only need the key with the maximum value, not the entire arrays of keys and values:

#!/usr/bin/env perl

use strict; use warnings;

my %hash = map { $_ => rand(10_000) } 'aa' .. 'zz';
my ($argmax) = sort { $hash{$b} <=> $hash{$a} } keys %hash;

print "$argmax => $hash{$argmax}\n";

Upvotes: 0

Alan Haggai Alavi
Alan Haggai Alavi

Reputation: 74252

Hashes have unordered keys. So, there is no such key as a first key in a hash.

However, if you need the key that sorts first (for maximum key value):

my %hash = (
    'foo' => 'bar',
    'qux' => 'baz',
);

my ($key) = sort { $b cmp $a } keys %hash;
print "$key => $hash{$key}";  # Outputs: qux => baz

Remember to use <=> instead of cmp for numerical sorting.

Upvotes: 8

run
run

Reputation: 1186

foreach my $key (sort keys(%hash)) { 
   print "$key" .  "$hash{$key}" . "\n"; 
   last;
} 

Upvotes: 0

Related Questions