in reply to scope of an autovivified variable?
I also assume the scope of this autovivified array is global,
It's not autovivified. It is explicitly created by my. Note that my does this at compile-time.
my @headerElements = split /\s+/, $headerStr if $headerStr;
«my ... if ...;» is not valid code. One cannot use a variable declared using my without first executing that my. This example is specifically documented in perlsyn ("NOTE: The behaviour ...").
The documentation is a bit suboptimal, since it doesn't mention «... and my ...;», «... ? my ... : ...;», etc,
I also assume the scope of this autovivified array is global
No, it's lexically scoped. Scope refers to where a variable is visible, accessible. That's why state variables are said to be lexically scoped too.
data is getting carried over from one iteration of the outer loop to the next, when it wouldn't if the array were lexical.
You are mistaken in your belief that lexical variables get deallocated at the end of their scope.
In the following, in the second call of f(), you can see effects the first call of f() had on $x:
$ perl -MDevel::Peek -e'sub f { my $x; Dump($x); $x="abc"; } f;f;' SV = NULL(0x0) at 0x93fcee0 REFCNT = 1 FLAGS = (PADMY) SV = PV(0x93eb040) at 0x93fcee0 REFCNT = 1 FLAGS = (PADMY) PV = 0x93f8e00 "abc"\0 CUR = 3 LEN = 4
Update: Fleshed out some details.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: scope of an autovivified variable?
by rmcgowan (Sexton) on May 11, 2011 at 20:37 UTC | |
by ikegami (Patriarch) on May 11, 2011 at 22:15 UTC | |
by rmcgowan (Sexton) on May 11, 2011 at 22:55 UTC | |
by Marshall (Canon) on May 12, 2011 at 15:03 UTC | |
by rmcgowan (Sexton) on May 11, 2011 at 23:05 UTC |