Perl Monk, Perl Meditation | |
PerlMonks |
Re: Variable scoping outside subsby Roger (Parson) |
on Oct 27, 2003 at 23:44 UTC ( [id://302573]=note: print w/replies, xml ) | Need Help?? |
Line 6 is never evaluated. When you uncomment line 3, you get the following compilation (not run-time) error: 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. If you move the line my $var = 1; to the end of the code (after sub test), you will get a compilation error. Back to your original code with line 3 commented out, when the Perl compiler gets to the line my $var = 1;, it create an entry in the package's global symbolic/variable table for $var, with the value being undef. And when the compiler gets to sub test later, it checks to see if $var exists in the symbol table, and found it. So the compilation succeeds. my $var = 1; has two components: 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. And the output is - 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.
In Section
Seekers of Perl Wisdom
|
|