Luke Luke - 11 months ago 148
Perl Question

Perl: find the max and min values in the array of hash

I have the structure below in Perl:

#!/usr/bin/perl
use strict;
use warnings;

my %hash = (
'firstitem' => {
'1' => ["A","99"],
'2' => ["B","88"],
'3' => ["C","77"],
},
'seconditem' => {
'3' => ["C","100"],
'4' => ["D","200"],
'5' => ["E","300"],
},
);


I am looking for a way to find the max number and min number in the array of each hash.
So the output will be

firstitem: max:99, min:77
seconditem: max:300, min:100


My idea is sorting the secondary key first and then do the bubble sort or other sorts in the for loop. It looks like not very elegant and smart.

foreach my $k1 (keys %hash) {
my $second_hash_ref = $hash{$k1};
my @sorted_k2 = sort { $a <=> $b } keys %{$second_hash_ref};
foreach my $i (0..$#sorted_k3){
#bubble sort or other sort
}
}

Answer Source

List::Util is a core module that provides the min and max functions:

use strict;
use warnings;

use List::Util qw(min max);

my %hash = (
    'firstitem' => {
        '1' => ["A","99"],
        '2' => ["B","88"],
        '3' => ["C","77"],
    },
    'seconditem' => {
        '3' => ["C","100"],
        '4' => ["D","200"],
        '5' => ["E","300"],
    },
);

for my $key (keys(%hash)) {
    my @numbers = map { $_->[1] } values(%{$hash{$key}});
    printf("%s: max: %d, min: %d\n", $key, max(@numbers), min(@numbers));
}

Output:

firstitem: max: 99, min: 77
seconditem: max: 300, min: 100
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download