in reply to Re: array looping with foreach
in thread array looping with foreach

It's fun to see all the variations (map/module/each/iter) but in my mind, the C-Style loop wins (mpeg4codec++). I've always used this construction, maybe it's just because I learned C long before Perl, but it's a clear and well known construction that doesn't create extra arrays, use Module.pm, or have the (probably trivial) function call overhead of iterators. I wonder if we don't occasionally try to be too Perlish just because this is NOT C.

Replies are listed 'Best First'.
Re^3: array looping with foreach
by plobsing (Friar) on Jan 19, 2008 at 01:26 UTC
    I wonder if we don't occasionally try to be too Perlish just because this is NOT C.
    I thought that was the point! We try to be Perlish because this isn't language X. Perhaps our definitions of "Perlish" differ.

    Familiarity is not a good argument as not everyone comes from C. I suspect people who came from say a lisp or python background would not immediately recognize a C style for loop.

    I will admit it is likely the most efficient, but, for me, that time is lost in correcting all my stupid off by one errors.
      I thought that was the point! We try to be Perlish because this isn't language X. Perhaps our definitions of "Perlish" differ.

      There really is no truly Perlish idiom for this situation. The idiom in OP's second example has some benefits: it's simple, doesn't require any extra modules, is hard to screw up, and lets you safely insert or delete from your array.

      But -- playing language designer for a moment -- could it be better?

      for my $i (0..$#array) { my $el = $array[$i]; ... };

      Hmm, too much repetition. Perhaps:

      over (@array) as ($el; $i) { ... };

      The array element and the index are implicitly localized to the loop, and the index is optional. If you want to iterate n-at-a-time you can do:

      over (@array) as ($el_a, $el_b; $i, $j) { ... };