Your last statement uses $VAR unqualified, so it is the last $VAR of whatsoever package that has been allocated - which happens to be the incarnation of $VAR in package C.
Consider:

use strict; use warnings; our $VAR=5.0; sub printit{print "Package Main VAR=$VAR\n";} package A; our $VAR=2.0; sub printit{print "Package A VAR=$VAR\n";} package B; our $VAR=3.0; sub printit{print "Package B VAR=$VAR\n";} package C; our $VAR=4.0; sub printit{print "Package C VAR=$VAR\n";} package main; $VAR="foo"; A::printit; B::printit; C::printit; printit; print "Package Main VAR=$VAR\n"; print <<EOH; A: $A::VAR B: $B::VAR C: $C::VAR main: $main::VAR whatever: $VAR EOH __END__ Package A VAR=2 Package B VAR=3 Package C VAR=foo Package Main VAR=5 Package Main VAR=foo A: 2 B: 3 C: foo main: 5 whatever: foo

Declaring a variable as our creates a lexically scoped variable spanning packages, which will create a symbol table slot in the current package in which the our declaration ocurred. This lexical variable will be bound to the symbol table of that package until re-declared (think bless) into another package. Altering the unqualified alias results in altering the value in the symbol table slot of that last package. That is why you get foo for $C::VAR above: $VAR - unqualified - is still bound to package C when it is last modified in package main.

If you remove the our declaration after package B, then $VAR will yield 3 for both package A and B.

perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'

In reply to Re: package variable scope by shmem
in thread package variable scope by santoshprasad

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.