Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
        }
    }
like image 402
Luke Avatar asked Dec 20 '25 03:12

Luke


1 Answers

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
like image 160
Matt Jacob Avatar answered Dec 23 '25 00:12

Matt Jacob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!