在Perl中,如何在散列中打印对应最大值的键? [英] In Perl, how can I print the key corresponding to the maximum value in a hash?

查看:140
本文介绍了在Perl中,如何在散列中打印对应最大值的键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能打印我的散列的第一个键和元素?



我已经有了一个排序的散列,但我只想打印第一个键和相应的值
谢谢,



感谢所有人在最后我将键和值推送到每个数组的两个不同的@array和print元素0,它的工作原理是:)

解决方案

哈希具有无序的键。因此,在散列中没有像第一个键那样的键。

然而,如果您需要先排序的键(最大值键值):

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

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

请记住使用< => 而不是 cmp 进行数字排序。


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

解决方案

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.

这篇关于在Perl中,如何在散列中打印对应最大值的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆