Ahhhh... and he was enlightened. Basically, $i here is operated on as if it was:
my $i;
foreach local $i (0 .. 5){
...
}
Do you have any ideas/pointers to the rationale for "no array members?" I understand that it is so, but fail to understand why it is so, when (for instance) one can local-ize individual array members.
for(split(" ","tsuJ rehtonA lreP rekcaH")){print reverse . " "}print "\b.\n";
| [reply] [d/l] [select] |
| [reply] |
#!/user/bin/perl
use warnings;
use strict;
my $i = 10;
print "$i\n";
foreach $i (0..5){
print "$i\n";
} # end foreach $i loop
print "$i\n";
exit(0);
It prints the following: 10
0
1
2
3
4
5
10
This is exactly what I believe the Camel says it should do since the loop variable is, if I recall correctly, always created anew as a lexical whose scope is the subsequent loop block (even though it appears to be created before the loop block). The output above seems to confirm that. I, like BrowserUk, however am a bit perplexed by the inability to use the $i[0] construct as the loop variable. Is it because the $i[0] implies a list structure which does not get created (via, for example, autovivification...spelling?)?
| [reply] [d/l] [select] |
Actually, the loop variable will be lexical if there's a current lexical variable with that name, otherwise it will be local variable (with a local scope).
my $i = 10;
our $j = 10;
sub print_it {say "[$i, $j]"}
print_it;
foreach $i (0 .. 5) {print_it;}
print_it;
foreach $j (0 .. 5) {print_it;}
print_it;
__END__
[10, 10]
[10, 10]
[10, 10]
[10, 10]
[10, 10]
[10, 10]
[10, 10]
[10, 10]
[10, 0]
[10, 1]
[10, 2]
[10, 3]
[10, 4]
[10, 5]
[10, 10]
As you can see, $i is lexical, and its value isn't visible outside the loop. But $j is a package variable, who gets a localized value inside the loop. And then its value is visible outside the loop. | [reply] [d/l] |
How could I get the for loop to use the predeclared $i instead of using a local one?
| [reply] [d/l] |
How could I get the for loop to use the predeclared $i instead of using a local one?
You don't, and that's a good thing. (You mean "foreach loop" there, I presume.)
| [reply] |
Well I have run into occasions where I would like use a previously declared variable as the loop variable in a situation like this. I know I can always just set a predeclared variable to be equal to the local loop variable, but that seems messier to me.
Don't get me wrong I really like the local loop variable feature I would just like to "turn it off" occasionally. I probably don't understand some basic concept here most likely...
| [reply] [d/l] |