Search code examples
arraysperlhashperl-data-structures

How do I access array elements stored in a hash?


I'm working on a script and trying to get some values from an array stored in a hash. After searching on Google, searching for questions on SO (and there are some with similar titles but which have remained unsolved or solve problems a little bit different than mine), and after checking out the Data Structures Cookbook and trying everything reasonable to try, I've come to ask your help.

I have a hash, $action, and an array, $action->{'Events'}. Here's the output for print Dumper($action->{'Events'});:

$VAR1 = [{
    'Muted'        => 'something',
    'Role'         => 'something',
    'Event'        => 'something',
    'Channel'      => 'something',
    'Talking'      => 'something',
    'UserNumber'   => 'somenumber',
    'CallerIDName' => 'somenumber',
    'Conference'   => 'somenumber',
    'MarkedUser'   => 'something',
    'ActionID'     => 'somenumber',
    'CallerIDNum'  => 'somenumber',
    'Admin'        => 'something'
}];

I need to get, for example, the value of $action->{'EVENTS'}->{'CallerIDName'}, but this syntax and many other won't work. I've even tried $action->{'EVENTS'}[6] and $action->{'EVENTS'}->[6] and so on.


Solution

  • It is Array of hashes, try this way:

    $action->{'EVENTS'}[0]->{'CallerIDName'}
    

    see perldsc for more detail.


    Updated example like:

    use strict;
    use warnings;
    use Data::Dumper;
    my $action = {};
    $action->{'Events'} = [{'Muted' => 'something',
                'Role' => 'something',
                'Event' => 'something',
                'Channel' => 'something',
                'Talking' => 'something',
                'UserNumber' => 'somenumber',
                'CallerIDName' => 'somenumber',
                'Conference' => 'somenumber',
                'MarkedUser' => 'something',
                'ActionID' => 'somenumber',
                'CallerIDNum' => 'somenumber',
                'Admin' => 'something'}];
    #push hash into the array of hashes
    push(@{$action->{'Events'}},{'Muted' => 'something',
                  'Role' => 'something1',
                  'Event' => 'something1',
                  'Channel' => 'something1',
                  'Talking' => 'something1',
                  'UserNumber' => 'somenumber1',
                  'CallerIDName' => 'somenumber1',
                  'Conference' => 'somenumber1',
                  'MarkedUser' => 'something1',
                  'ActionID' => 'somenumber1',
                  'CallerIDNum' => 'somenumber1',
                  'Admin' => 'something1'} );
     for(my $i=0; $i < @{$action->{'Events'}}; $i++){
        print Dumper($action->{Events}[$i]); #print entire hash in array index $i
        #print callerIDName key(any key) of each hash
        print Dumper($action->{'Events'}[$i]->{'CallerIDName'});  
     }