http://qs321.pair.com?node_id=761740


in reply to Re^2: foreach doesn't select array element
in thread foreach doesn't select array element

Your confusion may be coming from the order in which @ and [3] are being handled. @ first converts $fldref from an array reference into an array. Then it lets you use normal array element syntax, @$fldref[3], to access its elements. In other words, @$fldref[3] is equivalent to $fldref->[3].

You might be able to see this more clearly if we replace $fldref->[3] with a variable, like this:

my $aVars= [ ["\$a", "Tarina Babarista, pienest{ elefantista"], ["\$s", "(26'34); orkestroitu"], ["\$d", "Poulenc, Francis"], ["\$g", "Brunhoff, Jean de "], ["\$h", "P|ysti, Lasse"], ["\$j", "Fran*8aix, Jean"], ]; my $fldref= [ 500, 0, 0, $aVars ];

$fldref->[3] is $aVars, a reference to an array and not the dereferenced array, @$aVars. So when you loop on foreach (@$fldref[3]) you are really looping on foreach($fldref->[3]) which is just a loop over the single element $aVars. That is why you dump only once inside the foreach loop and see the $aVars array as a whole when you dump it rather than the individual elements of $aVars, each dumped separately.

If you want to loop on the contents of $fldref->[3] you have to dereference it yet again and do @{$fldref->[3]} or @{@fldref[3]}. This works as expected:

foreach my $tmp (@{$fldref->[3]}) { print "$tmp: <@$tmp>\n"; } #outputs ARRAY(0x814ec28) <$a Tarina Babarista, pienest{ elefantista> ARRAY(0x81e652c) <$s (26'34); orkestroitu> ARRAY(0x81e64fc) <$d Poulenc, Francis> ARRAY(0x81e5a4c) <$g Brunhoff, Jean de > ARRAY(0x81f236c) <$h P|ysti, Lasse> ARRAY(0x81f239c) <$j Fran*8aix, Jean>

Hope that helps, beth