in reply to Re: Quick easy question: What does $i mean?
in thread Quick easy question: What does $i mean?

I'm curious about the second bullet item in your reply. Is this the "better way" you were thinking of?
for (0 .. $limit) { #... }
What's wrong with the C-ish for loop?

I'm always looking for a better mousetrap!

Replies are listed 'Best First'.
Re^3: Quick easy question: What does $i mean?
by davidrw (Prior) on Sep 23, 2005 at 21:17 UTC
    cause we like the perl-ish way better :) But i think the point is that in perl, the array (assuming that's the context) indices themselves aren't needed. For example,
    for (my $i = 0; $i < $#array + 1; ++$i){ print $array[$i] . "\n"; }
    Is "better" written:
    foreach my $s ( @array ){ print "$s\n"; } # OR one of many other ways like: print $_."\n" for @array;
    Of course, if the output needs the array index in it, that changes things...
Re^3: Quick easy question: What does $i mean?
by ikegami (Patriarch) on Sep 23, 2005 at 21:29 UTC
    What's wrong with the C-ish for loop?

    It's harder to read. The index variable appears three times, and the upper bound is expressed as a logical expression, yet we think of the bound as a number. With a Perl-ish for loop, the index variable only appears once, and the bounds are expressed as numbers, just like in our mind.

    To support my case, let me point out you made an error reading the bounds of the C-ish version:

    for (0 .. $limit-1) { #... } ^^ was missing
      ... Assuming that $limit wasn't already defined as "whatever - 1". You're thinking of $limit strictly in terms of "scalar @array", which was not what I was thinking when I wrote that little snippet. :)

        No, I was not assuming anything.

        for (my $i = 0; $i < $limit; ++$i)
        is not equivalent to
        for (0 .. $limit) { #... }
        but rather
        for (0 .. $limit-1) { #... }