[Pdx-pm] for vs foreach question

Tom Phoenix rootbeer at redcat.com
Wed Dec 10 12:55:29 CST 2003

On Wed, 10 Dec 2003, Thomas Keller wrote:

> I thought the "foreach" keyword was a synonym for the "for" keyword.

Yes, but the loops are distinct. A foreach loop is not a for loop:

    for (1..10) { print "$_\n" }	# a foreach loop, in disguise
    foreach (1..10) { print "$_\n" }	# the same

    for ($_=1; $_<=10; $_++) { print "$_\n" }		# a true for loop
    foreach ($_=1; $_<=10; $_++) { print "$_\n" }	# the same

The difference is the semicolons inside the parens: If you've got two
semicolons, you've got a true for loop. No semicolons, it's a foreach.

> for (my $i = 0; $i < scalar @$aref; ++$i) {
> 	for (my $j = 0; $j < scalar @{$aref->[$i]}; ++$j) {

Here, $i and $j are index numbers which count from 0 up to the maximum

> foreach my $i (@$aref) {
> 	foreach my $j (@{$aref->[$i]}) {

But here, $i is an element of the array @$aref, so it's not a number. That
breaks the second loop's list expression, too.

I think you want something like this for those last two lines:

    foreach my $i (0..$#$aref) {
	foreach my $j (0..$#{$aref->[$i]}) {

Those use the same upper bound as the true for loop above.

Does that fix things for you? Good luck with it!

--Tom Phoenix

More information about the Pdx-pm-list mailing list