No need to declare $var and assign zero to it like you did in the first example. There really is no need to keep $var around after you have finished the loop. If you need to remember what it was, look at the array you were looping through. Rarely are you going to say (1..9) in any serious program, unless you love playing catch-up to scalability:for my $var (0..9){ #UPDATE: I changed 1-9 to 0-9 print $var; } #actually, this is better . . . but I digress . . . print (0..9);
will producemy @numbers = (0..9); foreach my $n (@numbers) { print $n; } print "\n", scalar(@numbers), "\n";
As for why this:0123456789 10
yields $var = 10 after it finishes, the reason is because that's how a C-style for loop works. Think about it. It _HAS_ to be 10, because $var increments 1 at a time . . .my $var; for ($var=1; $var < 10; ++$var){ print $var; } print "\n", $var, "\n";
Jeff
R-R-R--R-R-R--R-R-R--R-R-R--R-R-R--
L-L--L-L--L-L--L-L--L-L--L-L--L-L--
In reply to (jeffa) Re: (s)coping with foreach
by jeffa
in thread (s)coping with foreach
by greenFox
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |