mamesaye
mamesaye

Reputation: 2153

How do I access certain keys in a Perl nested hash?

I dumped a data structure:

print Dumper($bobo->{'issues'});

and got:

$VAR1 = {
    '155' => {
        'name' => 'Gender',
        'url_name' => 'gender'
    }
};

How can I extract 155?

How about if I have:

$VAR1 = {
    '155' => {'name' => 'Gender',  'url_name' => 'gender'},
    '11'  => {'name' => 'Toddler', 'url_name' => 'toddler'},
    '30'  => {'name' => 'Lolo',    'url_name' => 'lolo'}
};

I want to print one key, i.e. the first or second to see the value of the key?

Upvotes: 0

Views: 3235

Answers (2)

DavidO
DavidO

Reputation: 13942

So, based on the example you posted, the hash looks like this:

$bobo = {
    issues => {
        155 => {
            name     => 'Gender',
            url_name => 'gender',
        },
    },
};

'155' is a key in your example code. To extract a key, you would use keys.

my @keys = keys %{$bobo->{issues}};

But to get the value that 155 indexes, you could say:

my $val = $bobo->{issues}{155};

Then $val would contain a hashref that looks like this:

{
    name     => 'Gender',
    url_name => 'gender'
}

Have a look at perldoc perlreftut.

Upvotes: 2

mob
mob

Reputation: 118695

It is a key in the hash referenced by $bobo->{'issues'}. So you would iterate through

keys %{$bobo->{'issues'}}

to find it.

Upvotes: 1

Related Questions