in reply to Variable scoping outside subs
Because you have use strict; turned on, the Perl interpreter checks that a variable is created with my keyword before it is used, during the compilation stage.Global symbol "$var" requires explicit package name at p03.pl line 3. Execution of p03.pl aborted due to compilation errors.
The value of the $var is set at run-time. Because line 6 is never executed, the initial value of $var is undef when you call the subroutine test.my $var; # compile time component inserts variable into scratchpad # of the scope $var = 1; # run-time component assigns the value
And the output is -use strict; test(); #print "$var\n"; # Global symbol "$var" requires explicit... exit; my $var = 1; sub test { print "var was undef\n" if $var eq undef; print "var was '$var'\n"; $var++; print "var is now '$var'\n"; }
Updated: Thanks to welchavw for pointing out that the lexical variables are not stored in the package symbol tables. Instead, the lexical variables are stored in the scratchpad of the scope, file scope in this case.var was undef var was '' var is now '1'
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Variable scoping outside subs
by welchavw (Pilgrim) on Oct 28, 2003 at 01:39 UTC | |
by Roger (Parson) on Oct 28, 2003 at 03:13 UTC | |
|
Re: Re: Variable scoping outside subs
by xiper (Friar) on Oct 28, 2003 at 00:09 UTC |