none none - 1 year ago 76
Perl Question

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

Is the

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download