Why are variables declared with “our” visible across files?

半城伤御伤魂 提交于 2019-12-03 02:50:39

You can consider our to create a lexically-scoped alias to a package global variable. Package globals are accessible from everywhere; that's what makes them global. But the name created by our is only visible within the lexical scope of the our declaration.

package A;
use strict;
{
  our $var; # $var is now a legal name for $A::var
  $var = 42; # LEGAL
}

say $var; # ILLEGAL: "global symbol $var requires explicit package name"
say $A::var; # LEGAL (always)

{
  our $var; # This is the same $var as before, back in scope
  $var *= 2; # LEGAL
  say $var; # 84
}
FMc

You have a good answer already, but perhaps this will be helpful as well.

The our declaration combines aspects of my and use vars. It functions similarly to use vars in that it declares package variables; however, variables declared in this way are lexically scoped and cannot be accessed outside the scope in which they were declared (unless you use the fully qualified name of the variable). In addition, a variable declared with our is visible across its entire lexical scope, even across package boundaries.

Here's a table that I added to my Perl notes a while back. For an example, see this SO answer.

              Scope/     Package
              Namespace  Variable    Private    New
---------------------------------------------------
my            Lexical    No          Yes        Yes
our           Lexical    Yes         No         No
use vars      Package    Yes         No         No
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!