简体   繁体   中英

Perl, Help accessing value in hash of hashes

I have a hash of hashes, and I need to access a value, if the value o the same sub-hash matches string.

this is part of the hash I am trying to access:

{
  'ACCOUNTINFO' => {
                   'ENTRY' => [
                              {
                                'Name' => 'fields_12'
                              },
                              {
                                'Name' => 'fields_24'
                              },
                              {
                                'content' => 'Piso 12',
                                'Name' => 'TAG'
                              },
                              {
                                'Name' => 'fields_23'
                              },
                              ]
                   }
}

If Name is "Tag" I need the value of "content".

I can access Name:

$name = $refia->{ACCOUNTINFO}{ENTRY}{Name};

but I can't find any way to access content when needed.

I have gottend to this:

if ($refia->{ACCOUNTINFO}{ENTRY}{Name} eq "TAG") {
    ###
    }

Thanks

Let's look at the brackets:

{ { [ {

You have an HoHoAoH. You'll need the same brackets to dereference it:

$refia->{...}{...}[...]{...}

or more specifically,

$refia->{ACCOUNTINFO}{ENTRY}[$i]{Name};

But you don't know $i . In fact, you want to try a number of different values for $i , so you'll need a loop.

for my $i (0 .. $#{ $refia->{ACCOUNTINFO}{ENTRY} }) {
   if ($refia->{ACCOUNTINFO}{ENTRY}[$i]{Name} eq 'TAG') {
      ...
   }       
}

But that's a bit hard to follow. A much better solution is to narrow the focus to just the relevant part of the structure.

my $entries = $refia->{ACCOUNTINFO}{ENTRY};
for my $entry (@$entries) {
   if ($entry->{Name} eq 'TAG') {
      ...
   }       
}

ENTRY is pointing to an array. So you'd need to include the index (for example, get the first element):

$refia->{ACCOUNTINFO}{ENTRY}[0]{Name}

which is a short way of writing

$refia->{ACCOUNTINFO}->{ENTRY}->[0]->{Name}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM