print lowest value in hash of hashes

Viewed 91

I am experiencing issues completing a simple task. I have the following hash of hashes:

%hash = (
personA => {
    2017   => 1,
    2018   => 2,
},
personB => {
    2015   => 4,
    2013   => 28,
    2014   => 1, .
},
personC => {
    2013   => 3,
    2011   => 2,
    2012   => 45,
},
);

I am trying to print out the earliest year for each person, e.g. something like:

personA 2017

personB 2013

personC 2011

It seems that List::Util is the best tool for this, but I cannot find an example to adapt for my data. I am having trouble because the solutions I have found are trying to sort/print the first level of the hash (i.e., personA, etc.), as opposed to the years.

use strict;
use warnings;

my %hash;
my $hash; 

%hash = (
personA => {
    2017   => 1,
    2018   => 2,
},
personB => {
    2015   => 4,
    2013   => 28,
    2014   => 1,
},
personC => {
    2013   => 3,
    2011   => 2,
    2012   => 45,
},
);

use List::Util qw(min);
my $min = min keys %hash;
$hash = {$min => $hash->{$min}};
2 Answers

Loop through the people. Then, dereference each person hash to get a list of the years:

use warnings;
use strict;
use List::Util qw(min);

my %people = (
personA => {
    2017   => 1,
    2018   => 2,
},
personB => {
    2015   => 4,
    2013   => 28,
    2014   => 1,
},
personC => {
    2013   => 3,
    2011   => 2,
    2012   => 45,
},
);

for my $person (sort keys %people) {
    my $min = min(keys %{ $people{$person} });
    print "$person $min\n";
}

Outputs:

personA 2017
personB 2013
personC 2011

You can avoid using any module at all while keeping the simplicity.

use warnings;
use strict;

my %hash = (
    personA => {
        2017 => 1,
        2018 => 2,
    },
    personB => {
        2015 => 4,
        2013 => 28,
        2014 => 1,
    },
    personC => {
        2013 => 3,
        2011 => 2,
        2012 => 45,
    },
);

foreach my $person ( sort keys %hash ) {
    printf( "%s %d\n", $person, ( sort keys %{ $hash{$person} } )[0] );
}

( sort keys %{ $hash{$person} } )[0] - sorts the keys in a ascending order (which is by default) and then get the first one.

Related