[Pdx-pm] for vs foreach question

chromatic chromatic at wgz.org
Wed Dec 10 12:49:53 CST 2003

On Wed, 2003-12-10 at 10:37, Thomas Keller wrote:

> 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:

They're different loops altogether!

> #print 2-D array - this works fine
> for (my $i = 0; $i < scalar @$aref; ++$i) {

This loops through array indices.  You could also write it as:

	foreach (my $i = 0; $i < scalar @$aref; ++$i) {

> foreach my $i (@$aref) {

This loops through array elements.  You could also write it as:

	for my $i (@$aref) {

The synonymity only applies to the keyword itself.  It doesn't rewrite
loop conditions.

-- c

More information about the Pdx-pm-list mailing list