LesleyB has asked for the wisdom of the Perl Monks concerning the following question:
Hi
I have an array of hashes. Here is the output from Data::Dumper for some of it
$VAR1 = { 'divs' => [ 'Motion-work wheels after servicing', '2048x1536', 'DSCN0095.JPG' ], 'href' => '/p19581477.html' };
$VAR2 = { 'divs' => [ 'Movement without motion-work', '2048x1536', 'DSCN0096.JPG' ], 'href' => '/p19581478.html' }; $VAR3 = { 'divs' => [ 'Top view of bare movement', '2048x1536', 'DSCN0097.JPG' ], 'href' => '/p19581479.html' }; $VAR4 = { 'divs' => [ 'Movement without centre plate (1)', '2048x1536', 'DSCN0098.JPG' ], 'href' => '/p19581480.html' };
Now I first need to check my understanding of this is correct. Please correct me where I am wrong.
As far as I can determine, an array element here consists of a hash reference. The hash so referenced has two keys, 'divs' and 'href'. The value of the 'href' element is a string. The value of the 'divs' is an array reference.
This code works as I expect.
my $test = $pictures[2]; print $test."\n"; foreach my $ky (keys %$test) { print $ky." = ".$test->{$ky}."\n"; } my $yy = $test->{'divs'}; foreach my $xx (@$yy) { print $xx."\n";}
producing this output
HASH(0x831fa5c) divs = ARRAY(0x831da2c) href = /p19581479.html Top view of bare movement 2048x1536 DSCN0097.JPG
This code doesn't work
my $i = 0; foreach my $pic (@pictures) { print $i." href : ".$pic->{'href'}." divs : "; my $tmp = $pic->{'divs'}; #print @tmp." : "; #print $tmp," : ",@$tmp; #foreach my $div ($pic->{"divs"}) { print .", ".$div;} foreach my $xy (@$tmp) { print .", ".$xy; } print "\n"; $i++; }
producing this output
0 href : /p19581477.html divs : 1 href : /p19581478.html divs : 2 href : /p19581479.html divs : 3 href : /p19581480.html divs :
Spot the lack of text in the ouput.
I am at a loss to see what the difference is between
my $tmp = $pic->{'divs'}; foreach my $xy (@$tmp) { print .", ".$xy; }
and
my $yy = $test->{'divs'}; foreach my $xx (@$yy) { print $xx."\n";}
The only difference is the way in which the array element is selected being either a direct assigment my $test = $pictures[2]; or stepping through each element with a foreach loop.
Can anyone please explain what I am not understanding here?
Thanks in advance and looking forward to enlightenment.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Arrays of hashes which have arrays
by ikegami (Patriarch) on Jan 26, 2009 at 22:39 UTC | |
by LesleyB (Friar) on Jan 26, 2009 at 22:49 UTC | |
by ikegami (Patriarch) on Jan 26, 2009 at 22:58 UTC | |
|
Re: Arrays of hashes which have arrays
by kyle (Abbot) on Jan 26, 2009 at 22:40 UTC | |
|
Re: Arrays of hashes which have arrays
by clwolfe (Scribe) on Jan 27, 2009 at 18:27 UTC | |
by johngg (Canon) on Jan 27, 2009 at 22:56 UTC |