in reply to (s)coping with foreach
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--
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: (jeffa) Re: (s)coping with foreach
by greenFox (Vicar) on Apr 02, 2001 at 07:07 UTC | |
by jeffa (Bishop) on Apr 02, 2001 at 17:41 UTC | |
|
Re: (jeffa) Re: (s)coping with foreach
by extremely (Priest) on Apr 02, 2001 at 00:31 UTC | |
by Dominus (Parson) on Apr 02, 2001 at 05:58 UTC | |
by cLive ;-) (Prior) on Apr 02, 2001 at 04:47 UTC | |
by greenFox (Vicar) on Apr 02, 2001 at 06:43 UTC | |
by cLive ;-) (Prior) on Apr 02, 2001 at 07:05 UTC |