Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are variables declared with "our" visible across files?

From the "our" perldoc:

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

This means that variables declared with our should not be visible across files, because file is the largest lexical scope. But this is not true. Why?

like image 572
Eugene Yarmash Avatar asked Sep 02 '10 10:09

Eugene Yarmash


People also ask

How do you declare global variables in multiple files?

The clean, reliable way to declare and define global variables is to use a header file to contain an extern declaration of the variable. The header is included by the one source file that defines the variable and by all the source files that reference the variable.

What is variable visibility?

Visibility of a variable is defined by how a variable is accessible inside a program. A variable is visible within its scope and hidden outside the scope. A variable's visibility controls how much of the rest of the program may access it.

How do you make a variable accessible to all files in Python?

The best way to share global variables across modules across a single program is to create a config module. Just import the config module in all modules of your application; the module then becomes available as a global name. Hope it works!!


2 Answers

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
}
like image 191
hobbs Avatar answered Nov 16 '22 00:11

hobbs


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
like image 44
FMc Avatar answered Nov 15 '22 23:11

FMc