a7omiton
a7omiton

Reputation: 1617

How do you get nested key value of a hash in Perl?

I'd like to iterate over a hash ref and get keys if they exist, but the keys that I want are at the second level of the hash ref. I want to be able to get to this key for all first level keys of the hash ref that have it

Example:

    my $total = 0;
    foreach my $student (keys $students) {
        if ( exists $student->{???}->{points} ) {
            $total += $student->{points};
        }
    }
    return $total;

The problem I've run into is that I want to "not care" what the value of $student->{???} is, just want to get to the {points} for it

Upvotes: 0

Views: 417

Answers (1)

Miller
Miller

Reputation: 35208

You're mixing up your $students variable with your $student variable:

    if ( exists $student->{???}->{points} ) {
                ^^^^^^^^
                Should be $students

However, if you don't care about the keys of your first level HoH, then simply don't iterate on them.

Just iterate on the values instead:

use strict;
use warnings;

use List::Util qw(sum);

my $students = {
    bob => { points => 17 },
    amy => { points => 12 },
    foo => { info   => 'none' },
    bar => { points => 13 },
};

my $total = sum map { $_->{points} // 0 } values %$students;

print "$total is the answer\n";

Outputs:

42 is the answer

Upvotes: 2

Related Questions