Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Accessing and array of hashes

by Anonymous Monk
on Nov 26, 2014 at 14:37 UTC ( #1108457=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks!
I have this code structure and after passing the data to the sub routine “test” inside of the module, I am trying to accesses the items in the arrays, but I am getting an error saying that this is not a has reference.
What is the correct syntax to access each element once it gets passed to the sub without a loop?
Here is a sample that shows what I am trying to do:
use strict; user warnings; use info; use Data::Dumper; ... foreach my $in (@{$data{$key}}) { push @data , { name => $in{$key}[0]{ name }, add => $in{$key}[0]{ add }, street => $in{$key}[0]{ street }, city => $in{$key}[0]{ city }, zip => $in{$key}[0]{ zip }, state => $in{$key}[0]{ state }, }; } ... # Call and send data. info::test(\@data); ... # End file ... # file ... package info; use strict; use warnings; use Data::Dumper; ... sub test{ my ($test_data) = @_; print Dumper $test_data->{name}; } 1;

Thanks for looking!

Replies are listed 'Best First'.
Re: Accessing and array of hashes
by choroba (Cardinal) on Nov 26, 2014 at 14:42 UTC
    $test_data in info::test is an array reference, not a hash reference. You can't dereference it as a hash. What do you want to extract? The name of the first element?
    print $test_data->[0]{name};

    Or, the names of all the elements?

    print join ', ', map $_->{name}, @$test_data;
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      I need to access all of them, and it might be more them one block of the same key, so if I print:
      print $print_data->[0]{name}
      it prints 45 occurrences but with the same value.
        Need to use a loop:
        foreach my $detail (@{$test_data}){ my $name = $detail->{name}; print "$name\n"; }
Re: Accessing and array of hashes
by Eily (Monsignor) on Nov 26, 2014 at 15:45 UTC

    How do I post a question effectively?

    Please give us some useful data (for exemple a dump of @data, and %data, reduced down to a small representative subset) so that we can understand what you are talking about. Besides dumping your data might just show you what you have done wrong, because the mutliple use of $key, the existence of %data and @data, and the fact that you only ever look at the first element of your @{ $in{$key} } array make it look perly-wimey-wobly (strangely complex and unclear).

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1108457]
Approved by Corion
Front-paged by Corion
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (7)
As of 2022-11-28 12:49 GMT
Find Nodes?
    Voting Booth?