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

i think the point of that last bit was that "foreach" and "for" act differently. Foreach localizes the $var and for doesn't. And that after people keep telling you that they are the same thing and you can use "for" for "foreach" =)

--
$you = new YOU;
honk() if $you->love(perl)

Replies are listed 'Best First'.
Re: (s)coping with foreach
by Dominus (Parson) on Apr 02, 2001 at 05:58 UTC
    Says extremely:
    i think the point of that last bit was that "foreach" and "for" act differently.
    Definitely wrong. for and foreach are completely identical. Once Perl finishes compiling your program, it can't even remember which one you used.

    If you look in toke.c, you will see:

    case KEY_for: case KEY_foreach: ... code here that handles 'for' and 'foreach'
    This is in the vicinity of line 4145.
Re: (jeffa) - (s)coping with foreach
by cLive ;-) (Prior) on Apr 02, 2001 at 04:47 UTC
    Err,

    Do they? According to the camel:

    "The foreach keyword is actually a synonym for the for keyword, so you can use foreach for readability or for for brevity."

    - p100, Programming Perl, 2nd edition

    .02

    cLive ;-)

Re: Re: (jeffa) Re: (s)coping with foreach
by greenFox (Vicar) on Apr 02, 2001 at 06:43 UTC
    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';

      "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 ;-)