Line 6 is never evaluated.

When you uncomment line 3, you get the following compilation (not run-time) error:
Global symbol "$var" requires explicit package name at p03.pl line 3. Execution of p03.pl aborted due to compilation errors.
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:
my $var; # compile time component inserts variable into scratchpad # of the scope $var = 1; # run-time component assigns the value
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.

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"; }
And the output is -
var was undef var was '' var is now '1'
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 reply to Re: Variable scoping outside subs by Roger
in thread Variable scoping outside subs by xiper

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.