[Pdx-pm] for vs foreach question

Thomas Keller kellert at ohsu.edu
Wed Dec 10 12:37:06 CST 2003


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.




More information about the Pdx-pm-list mailing list