in reply to Risks of equivalence between FOR and FOREACH

I know of four kinds of for/foreach loops in Perl. In all cases, for and foreach are interchangeable. The interchangeability is documented in perlsyn.

My personal convention is to write counting loops and C-style loops using for, and iterating loops using foreach. That way, the extra cost of flattening the list is not hidden. However, Perl will gladly accept both for and foreach in every case.

Update: Since posting this, I have been told Reverse Iterating loop has been improved such that it no longer flattens the list, but the following snippet shows that it hasn't been "fixed" in the latest stable version of Perl (Perl 5.8.8).

use strict; use warnings; print("$]\n"); # 5.008008 # Don't inline these. It will cause the # memory to be allocated at compile time. my $min = 0; my $max = 10_000_000; for ( $min .. $max) { print(":"); <STDIN>; last; } # 2.2MB for (reverse $min .. $max) { print(":"); <STDIN>; last; } # 239MB

The person must have been misinterpreted perl586delta. perl586delta only says "a temporary reversed list isn't created". The temporary flattened list is still created.

Replies are listed 'Best First'.
Re^2: Risks of equivalence between FOR and FOREACH
by blazar (Canon) on Oct 31, 2006 at 23:10 UTC
    My personal convention is to write counting loops and C-style loops using for, and iterating loops using foreach. That way, the extra cost of flattening the list is not hidden. However, Perl will gladly accept both for and foreach in every case.

    And many people share your pov, while I'm of the "three chars are easier to type no matter what" school of thought - I also think we've "argued" about these issues in the past, but I'm not really sure. However to contribute with something concrete to this thread, it's also interesting if not properly relevant, to note that in Perl 6 the possible/alleged ambiguity will be removed, with C-style for loops being renamed to loop, and for being the preferred kind of loop for most situations, while foreach will be phased out:

    pugs> sub postfix:<!> (Int $x) { [*] 1..$x } undef pugs> say $_! for =<>; 3 6 4 24 7 5040 10 3628800 undef pugs>