in reply to Re: Hidden Secrets of PERL
in thread Hidden Secrets of PERL

Allow me to toil in some scrivener's work. In the "Non-Lexical Loop Iterators" section of PBP, the oracle speaks:
Always declare a for loop iterator variable with my.
and goes on to explain that, if there happens to be a lexical variable with the same name as the loop variable declared before the loop, that lexical variable is not reused within the loop, but a brand new independent lexical variable is implicitly created to take effect within the scope of the loop alone. Quoting the discussion there:
This behaviour is contrary to all reasonable expectation. Everywhere else in Perl, when you declare a lexical variable, it is visible throughout the remainder of its scope, unless another explicit my declaration hides it.
Update: wfsp sent me a link to this related node.

Replies are listed 'Best First'.
Re^3: Hidden Secrets of PERL
by Anonymous Monk on Oct 12, 2006 at 10:05 UTC
    The reason is history. The ability to write:
    foreach my $variable (LIST) {...}
    was relatively recent (5.004 I think). Before one had to write
    my $variable; foreach $variable (LIST) {...}

    As usual, it's combining old Perl DWIM, new features and backwards compatability that leads to oddities like this. Luckely, for most people, it all just works, and old programs don't break.