4.6.3. Discussion
The solutions assume you have a scalar variable containing the array
reference. This lets you do things like this:
@fruits = ( "Apple", "Blackberry" );
$fruit_ref = \@fruits;
foreach $fruit (@$fruit_ref) {
print "$fruit tastes good in a pie.\n";
}
Apple tastes good in a pie.
Blackberry tastes good in a pie.
We could have rewritten the foreach loop as a
for loop like this:
for ($i=0; $i <= $#$fruit_ref; $i++) {
print "$fruit_ref->[$i] tastes good in a pie.\n";
}
Frequently, though, the array reference is the result of a more
complex expression. Use the @{
EXPR } notation to turn the
result of the expression back into an array:
$namelist{felines} = \@rogue_cats;
foreach $cat ( @{ $namelist{felines} } ) {
print "$cat purrs hypnotically..\n";
}
print "--More--\nYou are controlled.\n";
Again, we can replace the foreach with a
for loop:
for ($i=0; $i <= $#{ $namelist{felines} }; $i++) {
print "$namelist{felines}[$i] purrs hypnotically.\n";
}