w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
accessing the highest value in hash of an hash in perl?

The following sorts the keys of each hashref by descending value, so the max is the first element returned:

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

Outputs:

fruits: pear
chocolates: snickers




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.