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

Hi Monks, still learning to handle datastructures here, having a bit of trouble with some data that looks like this:
$VAR1 = { 'Addresses' => { 'ArrayOfAddressResponse' => { 'AddressRespo +nse' => [ + { + 'CountyName' => 'NEW YORK', + 'Street2' => {}, + 'LastLine' => 'NEW YORK NY 10025-4857', + + }, + { + 'CountyName' => 'NEW YORK', + 'Street2' => {}, + 'LastLine' => 'NEW YORK NY 10025-4858', + + }, + { + 'CountyName' => 'NEW YORK', + 'Street2' => {}, + 'LastLine' => 'NEW YORK NY 10025-4808', etc.
So what I think I see here is a hash containing an Array reference, and indeed if I print:
$content->{Addresses}{ArrayOfAddressResponse}{AddressResponse}
I get an "ARRAYx..." So I'm thinking I'd like to iterate through that list and do something with the values, so I do:
foreach my $response ( $content->{Addresses}{ArrayOfAddressResponse}{A +ddressResponse} ) {...
But when I do this and print $response inside the loop, it tells me it's an ARRAY. I can even dereference the data within the loop with like $response->[0]{Street}. But that doesn't seem to make sense. What am I mis-conceptualizing, here? I guess the crux of it is I can't figure out what to put inside the foreach parentheses to let me iterate through the list of hashes. Any input would be greatly appreciated!

Replies are listed 'Best First'.
Re: Trouble dereferencing an array of hashes
by bobf (Monsignor) on Nov 05, 2009 at 03:59 UTC

    You are very close, and kudos for recognizing the hash of arrays (or more precisely, a hash of a hash of a hash of an array of hash references).

    foreach iterates over a list, not a reference (see perlsyn). In this case, you need to dereference the array before foreach can use it.

    foreach my $response ( @{ $content->{Addresses}{ArrayOfAddressResponse +}{AddressResponse} } ) { # do something with $response, which is a hash ref

      Thanks All! I thought I'd tried that but I'm thinking I must have tried it with the parent key, and so it complained that it wasn't an Array. Actually, now that I think about it, I'm positive that's what I did. Cool...thanks!
Re: Trouble dereferencing an array of hashes
by colwellj (Monk) on Nov 05, 2009 at 03:47 UTC
    Anon reply is right.
    Basically when you are referencing and get an output of ARRAYx Perl is telling you that it thinks you want the pointer or reference.
    Since you want the list you need to add @{} around your reference to explicitly tell Perl you know its actually a list you want and not a SCALAR reference.
    cheers
    John
Re: Trouble dereferencing an array of hashes
by Anonymous Monk on Nov 05, 2009 at 03:32 UTC