0

所以我有一个看起来像这样的哈希值:

my %hash = (
    'fruits' => {
        'apple'    => 34,
        'orange'   => 30,
        'pear'     => 45,
    },
    'chocolates' => {
        'snickers' => 35,
        'lindt'    => 20,
        'mars'     => 15,
    },
);

我只想访问数量最多的水果和数量最多的巧克力。输出应如下所示:

水果:梨巧克力:士力架

foreach my $item (keys %hash){
#print "$item:\t"; # this is the object name
foreach my $iteminitem (keys %{$hash{$item}})
    {
    my $longestvalue = (sort {$a<=>$b} values %{$hash{$item}})[-1]; #this stores the longest value
     print "the chocolate/fruit corresponding to the longestvalue" ;   

     #iteminitem will be chocolate/fruit name
    }
 print "\n";
}

我知道这并不难,但我正在消隐!

4

3 回答 3

2

下面按降序对每个 hashref 的键进行排序,因此 max 是返回的第一个元素:

my %hash = (
    chocolates => { lindt => 20, mars => 15, snickers => 35 },
    fruits     => { apple => 34, orange => 30, pear => 45 },
);

while (my ($key, $hashref) = each %hash) {
    my ($max) = sort {$hashref->{$b} <=> $hashref->{$a}} keys %$hashref;
    print "$key: $max\n";
}

输出:

fruits: pear
chocolates: snickers
于 2014-07-30T23:47:55.330 回答
0

这是另一种方式:

use strict;
use warnings;
use List::Util qw(max);

my %hash = (
    'fruits' => {
        'apple'    => 34,
        'orange'   => 30,
        'pear'     => 45,
    },
    "chocolates" => {
        'snickers' => 35,
        'lindt'    => 20,
        'mars'     => 15,
    },
);

for (keys %hash) {
    my $max = max values %{$hash{$_}};  # Find the max value 
    my %rev = reverse %{$hash{$_}};     # Reverse the internal hash
    print "$_: $rev{$max}\n";           # Print first key and lookup by max value
}

输出:

fruits: pear
chocolates: snickers
于 2014-07-31T00:15:16.423 回答
0

为此,您可能想要List::UtilsBy

use List::UtilsBy 'max_by';

my %hash = (
    chocolates => { lindt => 20, mars => 15, snickers => 35 },
    fruits     => { apple => 34, orange => 30, pear => 45 },
);

foreach my $key ( keys %hash ) {
    my $subhash = $hash{$key};
    my $maximal = max_by { $subhash->{$_} } keys %$subhash;
    print "$key: $maximal\n";
}

对于这个小例子,它可能并不重要,但对于更大的例子,有很大的不同。这将O(n)针对散列的大小及时运行,而“排序并获取第一个索引”解决方案将花费O(n log n)时间,慢得多,对键列表进行排序,然后丢弃除第一个结果之外的所有结果。

于 2014-07-31T07:30:16.697 回答