in reply to Using List::UtilsBy to print max and min values from a hash of hashes
Also, you used max_by even in the second paragraph where you wanted min_by.
After fixing these, it works as you expected:
#! /usr/bin/perl use warnings; use strict; use List::UtilsBy qw{ min_by max_by }; my %counts = ( Adam => { "201708" => 1, "201703" => 1, "201804" => 1, "201603" => 1, "201705" => 1, "201702" => 1, "201608" => 1, "201704" => 1, }, Sam => { "201803" => 1, "201801" => 1 }, ); for my $name ( keys %counts ) { my $subhash = $counts{$name}; my $maximal = max_by { $_ } keys %$subhash; print "$name, $maximal\n"; } for my $name ( keys %counts ) { my $subhash = $counts{$name}; my $minimal = min_by { $_ } keys %$subhash; print "$name, $minimal\n"; }
Update:
I also moved the use statement to the top (as it's executed during the compilation phase, anyway) and replaced foreach with its shorter form.
Note that you might use the minmax_by function, too:
use List::UtilsBy qw{ minmax_by }; for my $name ( keys %counts ) { my $subhash = $counts{$name}; my ($minimal, $maximal) = minmax_by { $_ } keys %$subhash; print "$name, $minimal - $maximal\n"; }
Update 2: But using { $_ } means you can get back to List::Util::min or max, or List::MoreUtils::minmax.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Using List::UtilsBy to print max and min values from a hash of hashes
by Izzy_Murph (Initiate) on Apr 13, 2020 at 16:42 UTC |