OK, I have the following code:
use strict;
my @ar = (1, 2, 3);
foreach my $a (@ar)
{
$a = $a + 1;
}
print join \", \", @ar;
and the outp
the important distinction here is that when you declare a my
variable in the initialization section of a for
loop, it seems to share some properties of both locals and lexicals (someone with more knowledge of the internals care to clarify?)
my @src = 1 .. 10;
for my $x (@src) {
# $x is an alias to elements of @src
}
for (@src) {
my $x = $_;
# $_ is an alias but $x is not an alias
}
the interesting side effect of this is that in the first case, a sub{}
defined within the for loop is a closure around whatever element of the list $x
was aliased to. knowing this, it is possible (although a bit odd) to close around an aliased value which could even be a global, which I don't think is possible with any other construct.
our @global = 1 .. 10;
my @subs;
for my $x (@global) {
push @subs, sub {++$x}
}
$subs[5](); # modifies the @global array