my declares a lexically scoped variable. A lexical scope continues until the closing brace (}) that ends the block it was defined in, or until the end of the file, whichever comes first.

{ package Foo; my $foo = 1; package Bar; # can still see $foo here package Baz; # can still see $foo here } # cannot see $foo any more

While our variables are associated with a particular package, they too are lexically scoped:

{ package Foo; our $foo = 1; # $foo is an alias for $Foo::foo package Bar; # $foo is still an alias for $Foo::foo here package Baz; # $foo is still an alias for $Foo::foo here } # cannot see $foo any more

For this reason, if you're defining multiple packages in the same file, it's a good idea to define them each within their own {...} block, so they don't accidentally leak variables. (Of course, sometimes - probably quite rarely - you'll actually want to share a lexical variable between the packages, in which case, just declare it right at the top before the first opening brace.)

package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name

In reply to Re: my $var masked across package scope? by tobyink
in thread my $var masked across package scope? by QM

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.