Given:
my @main_array = ();
my @sub_array1 = ( 1, 2, 3, 4, 5);
my @sub_array2 = ( "a", "b", "c", "d", "e" );
push @main_array, \@sub_array1;
push @main_array, \@sub_array2;
print "size of main_array is ",scalar(@main_array),"\n";
I want to foreach through the main_array and then foreach through the two arrays that it contains I have no idea what the syntax is for that.
Don't know if this is correct, but Perl seems to want a $ in the front of the foreach variable here. (doesn't like @$sub_array) I would also like to know the syntax to for loop through the main and sub as well.
foreach my $sub_array (@main_array)
{
print $sub_array; # prints ARRAY(0x213232)
# loop through each item in sub array
#foreach ...
}
Edit: So to summarize the answers given below (thanks to all):
use strict;
use warnings;
my @main_array = ();
my @sub_array1 = ( 1, 2, 3, 4, 5);
my @sub_array2 = ( "a", "b", "c", "d", "e" );
push @main_array, \@sub_array1;
push @main_array, \@sub_array2;
print "size of main_array is ",scalar(@main_array),"\n";
print "--------foreach ---------------------\n";
foreach my $sub_array (@main_array)
{
print "Sub array has ", scalar(@{$sub_array})," elements\n";
foreach my $value ( @{$sub_array})
{
print "value: ",$value,"\n";
}
}
print "--------------- for ----------------------- \n";
for (my $i = 0; $i < scalar(@main_array); $i++)
{
my $sub_array = $main_array[$i];
print "Sub array has ", scalar( @{$sub_array}), " elements\n";
for (my $j = 0; $j < scalar( @{$sub_array}); $j++)
{
print "value: ", $sub_array->[$j],"\n";
}
}
for my $v (@$sub_array) { .. }$sub_arrayis an array reference.