in reply to Looping trough Array Key/Value Pairs

See item 2 under Using References (or "Use Rule 1" in perlreftut), you can dereference any complex array references with @{...} and hash references with %{...}:

for my $hit ( @{ $VAR1->{hits}{hits} } ) { print "hit: '$hit->{_id}'\n"; for my $key ( keys %{ $hit->{_source} } ) { my $val = $hit->{_source}{$key}; print "key: '$key', val: '$val'\n"; } }

Outputs:

hit: 'AV6SrwuTv7sBjjRqMiW1' key: 'request', val: '/index.php' key: 'clientip', val: '192.168.1.1' hit: 'AV6UL-DOv7sBjjRqMidb' key: 'request', val: '/' key: 'clientip', val: '192.168.1.1'

Replies are listed 'Best First'.
Re^2: Looping trough Array Key/Value Pairs
by maikelnight (Sexton) on Sep 25, 2017 at 19:56 UTC

    Hi, first i'd like to say thanks to anyone who help here! I need to review all the stuff. I would like to ask Haukex -> i tried what you mentioned successfuly, but in my code it didnt work. I believe its because i posted the output of Data::Dumper ($VAR1). In my test case i did:

    @testarray = { '_shards' => { 'skipped' => 0, 'successful' => 5, 'total' => 5, 'failed' => 0 }, 'hits' => { 'hits' => [ { '_id' => 'AV6SrwuTv7sBjjRqMiW1', '_source' => { 'request' => '/inde +x.php', 'clientip' => '192. +168.1.1' }, '_type' => 'nginx', '_index' => 'nginx-2017.09.18', '_score' => '4.238926' }, { '_id' => 'AV6UL-DOv7sBjjRqMidb', '_source' => { 'clientip' => '192. +168.1.1', 'request' => '/' }, '_score' => '4.189655', '_type' => 'nginx', '_index' => 'nginx-2017.09.18' } ], 'total' => 2, 'max_score' => '4.238926' }, 'took' => 0, 'timed_out' => undef };

    And in that case what you mentioned dont work. I see you use $VAR1 (which works) but the goal would be to loop through an array with many elements....

      @testarray = { '_shards' => { 'skipped' => 0, 'successful' => 5, 'total' => 5, 'failed' => 0 }, ... };
      And in that case what you mentioned dont work. I see you use $VAR1 (which works) but the goal would be to loop through an array with many elements....

      A mental adjustment is needed here: initialized as shown,  @testarray is an array with a single element, an anonymous hash reference. If you can accommodate this properly in your code (or properly deal with an array with multiple elements), you will be on your way to your goal.

      Remember: Data::Dumper and Data::Dump (my favorite) are your friends.

      Update: Try this untested variation to haukex's posted code:

      for my $hashref (@testarray) { for my $hit ( @{ $hashref->{hits}{hits} } ) { print "hit: '$hit->{_id}'\n"; for my $key ( keys %{ $hit->{_source} } ) { my $val = $hit->{_source}{$key}; print "key: '$key', val: '$val'\n"; } } }


      Give a man a fish:  <%-{-{-{-<