In Perl, how can I print the key corresponding to

2019-02-11 08:53发布

问题:

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 :)

回答1:

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.



回答2:

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


回答3:

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


回答4:

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


回答5:

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


标签: perl hash