4.5. Iterating Over an Array by ReferenceProblemYou have a reference to an array, and you want to use SolutionUse # iterate over elements of array in $ARRAYREF
foreach $item (@$ARRAYREF) {
# do something with $item
}
for ($i = 0; $i <= $#$ARRAYREF; $i++) {
# do something with $ARRAYREF->[$i]
}DiscussionThe 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";
}
We could have rewritten the 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. You need to use the $namelist{felines} = \@rogue_cats;
foreach $cat ( @{ $namelist{felines} } ) {
print "$cat purrs hypnotically..\n";
}
print "--More--\nYou are controlled.\n";Again, we can replace the for ($i=0; $i <= $#{ $namelist{felines} }; $i++) {
print "$namelist{felines}[$i] purrs hypnotically.\n";
}See Alsoperlref (1) and perllol (1); Chapter 4 of Programming Perl; Recipe 11.1; Recipe 4.4 |