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?
our has the same scoping rules as my or state , meaning that it is only valid within a lexical scope. Unlike my and state , which both declare new (lexical) variables, our only creates an alias to an existing variable: a package variable of the same name.
my is used for local variables, whereas our is used for global variables. More reading over at Variable Scoping in Perl: the basics. Be careful tossing around the words local and global. The proper terms are lexical and package.
Global variables can be used inside any function or any block created within the program. It is visible in the whole program. Global variables can directly use and are accessible from every part of the program. Example 1: The variable $name is declared at the beginning of the code.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With