Kelly Jones wrote:
If I do a for loop in a subroutine, do I have to declare it private
with my()? I always though for() did that for me, but I ran into a bug
where code like this:

sub foo {for $i (1..2) {print $i;}}

affected my global $i (I think). Or was I imagining it?

The variable in a foreach loop is localized to the foreach loop and is an alias to each of the elements in the list.

$ perl -le'
use warnings;
use strict;
my $i = 8;
print $i;
for $i ( 1 .. 3 ) {
    print $i;
    }
print $i;
'
8
1
2
3
8

Here the lexical variable $i is declared in file scope but when it is used in the foreach loop its value outside the loop is not effected.

$ perl -le'
use warnings;
use strict;
my $i = 8;
print $i;
for my $i ( 1 .. 3 ) {
    print $i;
    }
print $i;
'
8
1
2
3
8

Here you have two different lexical $i variables, one in file scope, and one that is lexically scoped explicitly to the foreach loop.

Note that the foreach variable is an alias to the loop list so modifying the variable also modifies the list elements.




John
--
Those people who think they know everything are a great
annoyance to those of us who do.        -- Isaac Asimov

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to