SPUG: English-speak about Perl-speak "for" loops

Jack Foy jack at foys.net
Sat Sep 16 01:24:51 PDT 2006

Ingy dot Net wrote:
> Jack Foy wrote:
> > I assert that using the C-style for-loop is un-Perlish.  In most cases,
> > if you're numerically indexing your arrays, you're missing a better way
> > of expressing the code.
> How would you better express:
>     for (my $i = 0; $i < @array - 1; $i++) {
>         $array->[$i + 1] += $array[$i];
>     }
> The C style loop has its place in Perl.

Granted -- as do numerically indexed arrays!

I'll clarify the assertion a little: for most code written by most
people, foreach semantics provide a much more natural means of
expression than do C-style loops on a numeric index.

When we refactor code during reviews, this is one of the first points of
style I notice; it consistently provides a high rate of return in
clarity gained versus effort spent.  It also frequently reveals that the
entire operation further reduces cleanly to a map or grep statement,
which a traditional for-loop can obscure.

Thinking about Michael's original question: I might read the statement

	for my $element (@list) {

as "for my dollar element in at list open block", while

	for (my $i = 0; $i < @list; ++$i) {

might read "for open paren my dollar i gets zero, loop while dollar i
less than at list, plus plus dollar i close paren open block".  That's
wordy and leaves some syntax implied, but I use the construct so seldom
it hasn't been of benefit to optimize it.

Jack Foy <jack at foys.net>

More information about the spug-list mailing list