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

Re^3: foreach doesn't select array element

by ELISHEVA (Prior)
on May 04, 2009 at 14:37 UTC ( #761740=note: print w/replies, xml ) Need Help??

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

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://761740]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2022-05-29 09:47 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (101 votes). Check out past polls.