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

后端 未结 2 1720
被撕碎了的回忆
被撕碎了的回忆 2021-02-06 01:59

From the "our" perldoc:

our has the same scoping rules as my, but does not necessarily create a variable.

This means that vari

2条回答
  •  既然无缘
    2021-02-06 02:19

    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
    }
    

提交回复
热议问题