Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

How to address hashtables nested in arrays?

by benedicth (Initiate)
on Apr 11, 2015 at 20:40 UTC ( [id://1123155]=perlquestion: print w/replies, xml ) Need Help??

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

Hi I am trying to parse an XML into a nested Array/hash structure and am desperatly trying to get a list of keys from the Contact attributes which remains a hastable. Here is my code:

my $xml = <<'EOD' ; <root> <instance> <contact> <customerfid>101</customerfid> <firstname>Steve</firstname> <lastname>Jobs</lastname> </contact> <contact> <customerfid>102</customerfid> <firstname>mark</firstname> <lastname>blue</lastname> </contact> </instance> <instance> <contact> <customerfid>444</customerfid> <firstname>john</firstname> <lastname>Doe</lastname> </contact> </instance> </root> EOD my $data = XMLin( $xml, forcearray => ['instance', 'contact']) ; print Dumper( $data ) ; foreach $n (@{$data->{'instance'}}){ foreach $m (@{$data->{$n}{'contact'}}){ foreach $key (keys %{$data->{$m}}){ print "key: $key \n"; } } }

If I run parser this is my structure:

$VAR1 = { 'instance' => [ { 'contact' => [ { 'firstname' => 'Steve', 'customerfid' => '101', 'lastname' => 'Jobs' }, { 'firstname' => 'mark', 'customerfid' => '102', 'lastname' => 'blue' } ] }, { 'contact' => [ { 'firstname' => 'john', 'customerfid' => '444', 'lastname' => 'Doe' } ] } ] };

Why can't I address the hashtable the way I did and how would I do it? Thanks in advance!

Replies are listed 'Best First'.
Re: How to address hashtables nested in arrays?
by AnomalousMonk (Archbishop) on Apr 11, 2015 at 22:41 UTC
Re: How to address hashtables nested in arrays?
by pme (Monsignor) on Apr 11, 2015 at 20:59 UTC
    Hi benedicth,

    You can access the values this way:

    foreach my $n (@{$data->{instance}}) { foreach my $m (@{$n->{contact}}) { foreach my $key (keys %{$m}) { print "key: $key -> $m->{$key}\n"; } } }
      Thank you so much!! I'm still a newbie can you tell me why %{$data->{$m} does not work in this case?
        In this case both $n and $m contain hash reference but in %{$data->{$m}} $m should be a key.

        Try to run your script in perl debugger (perldebug) and check $n and $m using 'x' command for better understanding.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1123155]
Approved by graff
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (7)
As of 2024-04-24 17:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found