In Perl, how can I print the key corresponding to

2019-02-11 09:10发布

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

标签: perl hash
5条回答
唯我独甜
2楼-- · 2019-02-11 09:33

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楼-- · 2019-02-11 09:35

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.

查看更多
我想做一个坏孩纸
4楼-- · 2019-02-11 09:49

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";
查看更多
ら.Afraid
5楼-- · 2019-02-11 09:55

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];
查看更多
姐就是有狂的资本
6楼-- · 2019-02-11 09:56
foreach my $key (sort keys(%hash)) { 
   print "$key" .  "$hash{$key}" . "\n"; 
   last;
} 
查看更多
登录 后发表回答