I am currently cleaning up some old code - among other things to comply with the strict pragma - and need to know the semantics of assigning/declaring package variables. Given the simple example
package P; $A = 'something';
then strict complains about $A missing an explicit package name. That's ok, it's what strict is supposed to do. In an effort to understand and decide on the best way to fix this, I tried the following short program:
package main; my $A = 123; $::A = 456; print ('package '.__PACKAGE__."\n"); print ('$A is '.$A."\n"); print ('our $A is '.our $A."\n"); print ('$::A is '.$::A."\n"); print ('$main::A is '.$main::A."\n"); print ('$main\'A is '.$main'A."\n");
which generates the following output:
package main $A is 123 our $A is 456 $::A is 456 $main::A is 456 $main'A is 456
It's the 2nd line that caught my attention. Apparently, $A (declared globally) and $::A are not the same variable. Is this correct? I seem to have missed that in the Perl documentation. And exactly what happens during the assignment (without declaration) in the first example? Does the reference to $A get converted to $P::A because of the package statement, resulting in that variable being created during the assignment?

Discussion eqilogue - added after a couple of days

Thank you all for eventually guiding me towards the right track. The reference to the tutorial "Coping with Scoping" was especially useful. This tutorial is very precise and informative. Please bear in mind that my question was about (old) non-strict code - not best practice for the future. At least with non-strict code, the difference between a lexical alias and what used to be called a "package variable" can matter a great deal.

In reply to how to declare a package variable by scigeek

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.