cooldood3490
cooldood3490

Reputation: 2498

Perl Hash of Hashes, get lowest numeric key

I have a hash of hashes where the first key is a string and the second key is an integer. I'm trying to get the lowest second key in the hash of hashes. Here's my hash.

%HoH = (
    flintstones => {
        8 => "fred",
        4 => "barney",
    },
    jetsons => {
        5 => "george",
        1 => "jane",
        9 => "elroy",    # Key quotes needed.
    },
    simpsons => {
        99 => "homer",
        5  => "marge",
        3  => "bart",
    },
);

How do I get the lowest (minimum) key for the hash simpsons? In this case the answer would be 3. The closest related search I could find was for a way to get the key with the highest value. But I'm trying to get the key with the lowest numeric value.

================== EDIT ============ MY ATTEMPT ================

foreach my $cartoon (keys %HoH){
    if ($cartoon == "simpsons"){
        $HoH{$cartoon}{<numeric key>};   # somehow store and print lowest key
    }
}

I can't loop through the keys sequentially (1,2,3,4, etc.) and simply store and return the lowest key because the key (1,2,3,4, etc.) may not exist. I probably would have tried to store the keys in a separate array and get the minimum key stored in that array. That's my attempt. It's sort of a round about way of doing it. Since it's a round about way, next I would have done more Googling to see if there's an easier way (a one liner way) to do it.

Upvotes: 2

Views: 713

Answers (2)

Andrey
Andrey

Reputation: 1818

my $min = (sort {$a <=> $b} keys $HoH{'simpsons'})[0];
print $min;

Upvotes: 3

Matt Jacob
Matt Jacob

Reputation: 6553

use List::Util qw(min);
print min(keys(%{$HoH{simpsons}}));

Upvotes: 8

Related Questions