http://www.perlmonks.org?node_id=410204


in reply to Pearls (not really) of Perl programming

for (1..10) { my $i = $_; # some stuff with $i }

Replies are listed 'Best First'.
Re^2: Pearls (not really) of Perl programming
by ikegami (Patriarch) on Nov 24, 2004 at 19:55 UTC

    I've done that! For two reasons, one good, one bad.

    Bad Reason

    I thought

    for my $i (1..10) { # some stuff with $i }

    was the same as

    my $i; for $i (1..10) { # some stuff with $i }

    rather than being the same as

    { my $i; for $i (1..10) { # some stuff with $i } }

    because in C++, (IIRC)

    for (int i=0, i<5; i++) { ... } // i in still in scope here!
    .

    I didn't do use int as shown here, but my coworkers did and I would find it misleading. Perl doesn't have that problem, but I only learned that recently.

    Good Reason

    This fails ('Modification of a read-only value attempted')

    foreach my $var ('a', 'b') { ...something that may modify $var... print($var); }

    but this doesn't

    foreach ('a', 'b') { my $var = $_; ...something that may modify $var... print($var); }

      Your good reason has a corollary, which happens to be another good reason to use the original code. This modifies the original array:

      @array = 1 .. 10; for my $var (@array) { $var++; print "$var\n"; } print "@array\n";

      But this does not:

      @array = 1 .. 10; for (@array) { my $var = $_; $var++; print "$var\n"; } print "@array\n";
      Actually, I believe that the C++ behaviour you pointed out is an MSVC glitch.
      for(int i = 0; ;) { }
      ... should have "i" visible only inside the for loop. I think gcc actually does this properly, as does MSVC .NET. ... unless I'm horribly wrong?

        Close... VC++ .NET allows it, gcc 2.95.4 forbids it.

        a.cpp

        #include <stdio.h> int main() { for (int i=0; i<5; i++) { printf("%d\n", i); } printf("%d\n", i); return 0; }

        VC++ .NET

        >cl a.cpp Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.3077 for +80x86 Copyright (C) Microsoft Corporation 1984-2002. All rights reserved. a.cpp Microsoft (R) Incremental Linker Version 7.10.3077 Copyright (C) Microsoft Corporation. All rights reserved. /out:a.exe a.obj >a 0 1 2 3 4 5

        gcc 2.95.4

        $ gcc a.cpp -o a a.cpp: In function `int main()': a.cpp:9: name lookup of `i' changed for new ANSI `for' scoping a.cpp:5: using obsolete binding at `i'
Re^2: Pearls (not really) of Perl programming
by PetaMem (Priest) on Nov 25, 2004 at 08:55 UTC
    Oh yes!

    Seen that. Especially guys coming from the chr(ord('A')+2) programming language cannot get rid of the indexing-loop concept in their head.

    Bye
     PetaMem
        All Perl:   MT, NLP, NLU