Just another Perl shrine PerlMonks

### Help with finding the min and max values of an HoA

 on Jun 21, 2014 at 09:22 UTC Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,
I am a bit stuck using an Hash of Arrays...
So, if I print the elements, I get something like this:
```id1:  0 = 1 1 = 25
id2:  0 = 1 1 = 33 2 = 0 3 = 86
id3:  0 = 1 1 = 33
id4:  0 = 1 1 = 24 2 = 24 3 = 119 4 = 24 5 = 108
id5:  0 = 1 1 = 20 2 = 0 3 = 56
id6:  0 = 29 1 = 345

How can I find, for each id, which are the minimum and maximum values of its respective array? For example, for id4, I would like to get 1 and 119 respectively.

Replies are listed 'Best First'.
Re: Help with finding the min and max values of an HoA
by AppleFritter (Vicar) on Jun 21, 2014 at 09:40 UTC
Use List::Util:
```#!/usr/bin/perl

use List::Util qw(min max);
use feature qw(say);

%hash = (
'id1' => [ 1, 25 ],
'id2' => [ 1, 33, 0, 86 ],
'id3' => [ 1, 33 ],
'id4' => [ 1, 24, 24, 119, 24, 108 ],
'id5' => [ 1, 20, 0, 56 ],
'id6' => [ 29, 345 ],
);

foreach (sort keys %hash) {
say "\$_: min=" . min(@{\$hash{\$_}}) . ", max=" . max(@{\$hash{\$_}});
}
Output:
```id1: min=1, max=25
id2: min=0, max=86
id3: min=1, max=33
id4: min=1, max=119
id5: min=0, max=56
id6: min=29, max=345
HTH!
Re: Help with finding the min and max values of an HoA
by AnomalousMonk (Chancellor) on Jun 21, 2014 at 10:23 UTC

This does the same thing as above, but puts the results into a new hash for future use:

```c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le
"use List::Util qw(min max);
;;
my %hash = (
id1 => [ 1, 25, ],
id2 => [ 1, 33, 0, 86, ],
id3 => [ 1, 33, ],
id4 => [ 1, 24, 24, 119, 24, 108, ],
id5 => [ 1, 20, 0, 56, ],
id6 => [ 29, 345, ],
);
dd \%hash;
;;
my %minmax =
map  { my \$ar = \$hash{\$_};  \$_ => [ min(@\$ar), max(@\$ar) ] }
keys %hash
;
dd \%minmax;
"
{
id1 => [1, 25],
id2 => [1, 33, 0, 86],
id3 => [1, 33],
id4 => [1, 24, 24, 119, 24, 108],
id5 => [1, 20, 0, 56],
id6 => [29, 345],
}

{
id1 => [1, 25],
id2 => [0, 86],
id3 => [1, 33],
id4 => [1, 119],
id5 => [0, 56],
id6 => [29, 345],
}
Thanks a lot guys!
Much appreciated!

Create A New User
Node Status?
node history
Node Type: perlquestion [id://1090744]
Approved by Corion
Front-paged by perlfan
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (8)
As of 2018-03-17 15:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
When I think of a mole I think of:

Results (224 votes). Check out past polls.

Notices?