Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

strict

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?

like image 765
Acsor Avatar asked Jul 17 '13 20:07

Acsor


People also ask

What is the difference between my and our in Perl?

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.

What is the difference between my and our?

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.

What is global variable in Perl?

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.


1 Answers

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.

like image 115
amon Avatar answered Oct 20 '22 01:10

amon