[Pdx-pm] for vs foreach question

Jeff Lavallee jeff at zeroclue.com
Wed Dec 10 12:45:29 CST 2003


In a foreach loop $i and $j don't get set to the indicies of the
array, they are the actual elements of the array.  I think you want
something like this:

foreach my $i (@$aref) {
        foreach my $j (@$i) {
                print $j, " ";
        }
        print "\n";
}


I haven't been very verbose or perhaps even clear in my explanation, so if
it doesn't make sense, holler...


jeff


On Wed, 10 Dec 2003, Thomas Keller wrote:

> Hi all,
> I thought the "foreach" keyword was a synonym for the "for" keyword. So
> I'm perplexed why the following loops don't give the same output:
> ############# code snippet ############
> my $aref = [ ['Tom', 'Pattie', 'Dave', 'Dan', 'John'],
> 				['Lee', 'Mike', 'Anita','Kathryn', 'Cecelia'],
> 				['Cybele','Tomas','BenJoaquin','Anna'],
> 				['Nick','Sam','Kate'],['Kim','Mike'],
> 				['Brian','Marissa'],
> 				['null'] ];
>
> #print 2-D array - this works fine
> for (my $i = 0; $i < scalar @$aref; ++$i) {
> 	for (my $j = 0; $j < scalar @{$aref->[$i]}; ++$j) {
> 		print $aref->[$i][$j], " ";
> 	}
> 	print "\n";
> }
>
> #print 2-D array - ?? - doesn't work
> foreach my $i (@$aref) {
> 	foreach my $j (@{$aref->[$i]}) {
> 		print $aref->[$i][$j], " ";
> 	}
> 	print "\n";
> }
>
> ###########
> Thanks for any help understanding this.
> Tom K.
>
> _______________________________________________
> Pdx-pm-list mailing list
> Pdx-pm-list at mail.pm.org
> http://mail.pm.org/mailman/listinfo/pdx-pm-list
>



More information about the Pdx-pm-list mailing list