Are there any differences between our defined variables and normal global variables in Perl?

StackOverflow https://stackoverflow.com/questions/17709834

  •  03-06-2022
  •  | 
  •  

Вопрос

Is the our modifier only used when strict pragma is active to let using global variables or is it even used for some extra features different from normal global variables when strict is off?

Это было полезно?

Решение

Yes, our declarations can have additional features when compared with undeclared globals. But these are largely irrelevant.

our creates a lexical alias to a global variable (of the same name). That is, in package Foo, our $bar and $Foo::bar refer to the same variable. However, the former is only available in a tight lexical scope.

As our has a lexical effect, the alias can also shadow lexical variables with my:

our $foo = 42; # give some value
my  $foo = -1; # same name, different value
say "my  gives $foo";
our $foo;      # reintroduce the alias; shadow lexical
say "our gives $foo";

If you strip the our declarations and run it without strict, this obviously won't give the output

my  gives -1
our gives 42

Just like my, our can take a bit extra declaration syntax, e.g. attributes:

use threads::shared;
our $foo :shared;

You can also specify a type for usage with the fields pragma:

our Foo $foo;

This can't be done for global variables without our.

Другие советы

As you can see from the perldocs, our creates an alias to a package variable with the same name as the oured variable in the current package.

If you're writing code that has multiple package definitions in it, you could use an oured variable to pass an aliased variable between modules.

package Foo:
our $bar = 42;  # $bar is an alias for $Foo::bar

package Baz;
print $bar;     # prints '42', since $bar is $Foo::bar

Thus, a usage that has nothing to do with global variables.

Global, package variables are accessible anywhere, whether strict is in place or not, if you specify the fully-qualified name, i.e. you prefix it with the package name. So I can access $main::variable anywhere at any time.

Without strict, if you access $variable that you haven't declared with my, Perl assumes it is a package variable in the current package. our can be used to explicitly declare a package variable, but without strict it doesn't do much as anything undeclared behaves the same way.

With strict in place, variables declared with our are accessible using their local name as well as their fully-qualified name, in the lexical scope where the declaration appeared. That means that to access a global variable from two subroutines you must either declare it within both subroutines or declare it before both of them at an outer scope.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top