in reply to Re: (jeffa) Re: (s)coping with foreach
in thread (s)coping with foreach

Well that wasn't the point I was trying to make :) I tried this though
my $var=0; foreach ($var=1; $var < 10; ++$var){ print $var; } print "\n$var \n";

it appears that when used with a c style loop for/foreach does not localise the index variable... and for the record I have never written a loop with the index variable other than the normal syntax of for (my $var;... :-)

--
my $chainsaw = 'Perl';

Replies are listed 'Best First'.
Re: (s)coping with foreach
by cLive ;-) (Prior) on Apr 02, 2001 at 07:05 UTC
    "Well that wasn't the point I was trying to make :)"

    I know, but... hmmm.

    Getting back to your questions...

    Let's rewrite your loop:

    my $var=0; { $var=1; while ($var < 10) { print "$var"; $var++; } } print "\n$var \n";

    The for loop adds to $var, then checks condition, then breaks loop. It doesn't say would I break the condition if I added one to $var, so $var is 10.

    Also, you don't declare $var as being local to the loop. So, look at this:

    my $var=0; foreach (my $var=1; $var < 10; ++$var){ print $var; } print "\n$var \n";

    Or, as written above:

    my $var=0; { my $var=1; while ($var < 10) { print "$var"; $var++; } } print "\n$var \n";

    Seem clearer now?

    cLive ;-)