I am doing some code golf, and decided to try and be 'smart' and declare a subroutine where it would have the variables it needs already in scope, to avoid the extra code of having to pass in the arguments:
#! perl
use strict;
use warnings;
for my $i(0..1) {
my @aTest = (1);
sub foo {
# first time round - @aTest is (1)
# second time round - @aTest is (1,2)
push @aTest, 2;
# first time round - @aTest is (1,2)
# second time round - @aTest is (1,2,2)
my $unused = 0;
}
foo();
}
foo
sees the variable @aTest
, and it has the expected value of (1)
the first time I enter foo
, before it pushes 2
onto the array as well. @aTest
now looks like (1,2)
.
So far so good.
Then we exit foo
, and commence the second round of the for loop. @aTest
is reassigned to (1)
again.
We enter foo
for the second time, but @aTest
retains the value it previously had in foo
(i.e. (1,2)
), and then pushes another 2
on to become (1,2,2)
.
What's going on here?
I assumed that since @aTest
was in the same scope, it would be referring to the same variable both insed and outside foo
. So how is it that inside `foo it retains its old value?