Forum Moderators: coopster & phranque

Message Too Old, No Replies

Is there a $ shortcut in a for() loop, like there is in a foreach()?

         

csdude55

7:20 am on May 4, 2019 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I recently discovered that the $_ variable is implicitly defined in a foreach loop, like so:

@array = ('a', 'b', 'c');

foreach (@array) {
print $_;
# a
# b
# c
}


(I guess that, technically speaking, I wouldn't even have to print $_;, I could just use print; for the same result... but that's beside the point for my question.)

I understand that for() is more or less an alias for foreach(). So for the sake of my own knowledge, when I do this:

@array = ('a', 'b', 'c');

for ($i = 0; $i <= $#array; $i++) {
print $array[$i];
}


is there an implicit variable that would already mean $array[$i], similar to the $_ in the foreach?

From my own testing I'm almost positive that there's not, but I wanted to make sure.

phranque

9:40 am on May 4, 2019 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



from the perlsyn manpage:
The foreach keyword is actually a synonym for the for keyword...


from the "camel book":
the foreach statement provides a list context to the expression in parentheses


whereas:
the for loop takes three expressions...


which means you don't have an implicit array with the for loop.