I know what my is in Perl. It defines a variable that exists only in the scope of the block in which it is defined. What does our do?
How does our differ from my?
How does our differ from my and what does our do?
In Summary:
Available since Perl 5, my is a way to declare non-package variables, that are:
private
new
non-global
separate from any package, so that the variable cannot be accessed in the form of $package_name::variable.
On the other hand, our variables are package variables, and thus automatically:
global variables
definitely not private
not necessarily new
can be accessed outside the package (or lexical scope) with the
qualified namespace, as $package_name::variable.
Declaring a variable with our allows you to predeclare variables in order to use them under use strict without getting typo warnings or compile-time errors. Since Perl 5.6, it has replaced the obsolete use vars, which was only file-scoped, and not lexically scoped as is our.
For example, the formal, qualified name for variable $x inside package main is $main::x. Declaring our $x allows you to use the bare $x variable without penalty (i.e., without a resulting error), in the scope of the declaration, when the script uses use strict or use strict "vars". The scope might be one, or two, or more packages, or one small block.
The PerlMonks and PerlDoc links from cartman and Olafur are a great reference - below is my crack at a summary:
my variables are lexically scoped within a single block defined by {} or within the same file if not in {}s. They are not accessible from packages/subroutines defined outside of the same lexical scope / block.
our variables are scoped within a package/file and accessible from any code that use or require that package/file - name conflicts are resolved between packages by prepending the appropriate namespace.
Just to round it out, local variables are "dynamically" scoped, differing from my variables in that they are also accessible from subroutines called within the same block.
An example:
use strict;
for (1 .. 2){
# Both variables are lexically scoped to the block.
our ($o); # Belongs to 'main' package.
my ($m); # Does not belong to a package.
# The variables differ with respect to newness.
$o ++;
$m ++;
print __PACKAGE__, " >> o=$o m=$m\n"; # $m is always 1.
# The package has changed, but we still have direct,
# unqualified access to both variables, because the
# lexical scope has not changed.
package Fubb;
print __PACKAGE__, " >> o=$o m=$m\n";
}
# The our() and my() variables differ with respect to privacy.
# We can still access the variable declared with our(), provided
# that we fully qualify its name, but the variable declared
# with my() is unavailable.
print __PACKAGE__, " >> main::o=$main::o\n"; # 2
print __PACKAGE__, " >> main::m=$main::m\n"; # Undefined.
# Attempts to access the variables directly won't compile.
# print __PACKAGE__, " >> o=$o\n";
# print __PACKAGE__, " >> m=$m\n";
# Variables declared with use vars() are like those declared
# with our(): belong to a package; not private; and not new.
# However, their scoping is package-based rather than lexical.
for (1 .. 9){
use vars qw($uv);
$uv ++;
}
# Even though we are outside the lexical scope where the
# use vars() variable was declared, we have direct access
# because the package has not changed.
print __PACKAGE__, " >> uv=$uv\n";
# And we can access it from another package.
package Bubb;
print __PACKAGE__, " >> main::uv=$main::uv\n";
Coping with Scoping is a good overview of Perl scoping rules. It's old enough that our is not discussed in the body of the text. It is addressed in the Notes section at the end.
The article talks about package variables and dynamic scope and how that differs from lexical variables and lexical scope.
The perldoc has a good definition of our.
Unlike my, which both allocates storage for a variable and associates a simple name with that storage for use within the current scope, our associates a simple name with a package variable in the current package, for use within the current scope. In other words, our has the same scoping rules as my, but does not necessarily create a variable.
my is used for local variables, whereas our is used for global variables.
More reading over at Variable Scoping in Perl: the basics.
I ever met some pitfalls about lexical declarations in Perl that messed me up, which are also related to this question, so I just add my summary here:
1. Definition or declaration?
local $var = 42;
print "var: $var\n";
The output is var: 42. However we couldn't tell if local $var = 42; is a definition or declaration. But how about this:
use strict;
use warnings;
local $var = 42;
print "var: $var\n";
The second program will throw an error:
Global symbol "$var" requires explicit package name.
$var is not defined, which means local $var; is just a declaration! Before using local to declare a variable, make sure that it is defined as a global variable previously.
But why this won't fail?
use strict;
use warnings;
local $a = 42;
print "var: $a\n";
The output is: var: 42.
That's because $a, as well as $b, is a global variable pre-defined in Perl. Remember the sort function?
2. Lexical or global?
I was a C programmer before starting using Perl, so the concept of lexical and global variables seems straightforward to me: it just corresponds to auto and external variables in C. But there're small differences:
In C, an external variable is a variable defined outside any function block. On the other hand, an automatic variable is a variable defined inside a function block. Like this:
int global;
int main(void) {
int local;
}
While in Perl, things are subtle:
sub main {
$var = 42;
}
&main;
print "var: $var\n";
The output is var: 42. $var is a global variable even if it's defined in a function block! Actually in Perl, any variable is declared as global by default.
The lesson is to always add use strict; use warnings; at the beginning of a Perl program, which will force the programmer to declare the lexical variable explicitly, so that we don't get messed up by some mistakes taken for granted.
This is only somewhat related to the question, but I've just discovered a (to me) obscure bit of perl syntax that you can use with "our" (package) variables that you can't use with "my" (local) variables.
#!/usr/bin/perl
our $foo = "BAR";
print $foo . "\n";
${"foo"} = "BAZ";
print $foo . "\n";
Output:
BAR
BAZ
This won't work if you change 'our' to 'my'.
print "package is: " . __PACKAGE__ . "\n";
our $test = 1;
print "trying to print global var from main package: $test\n";
package Changed;
{
my $test = 10;
my $test1 = 11;
print "trying to print local vars from a closed block: $test, $test1\n";
}
&Check_global;
sub Check_global {
print "trying to print global var from a function: $test\n";
}
print "package is: " . __PACKAGE__ . "\n";
print "trying to print global var outside the func and from \"Changed\" package: $test\n";
print "trying to print local var outside the block $test1\n";
Will Output this:
package is: main
trying to print global var from main package: 1
trying to print local vars from a closed block: 10, 11
trying to print global var from a function: 1
package is: Changed
trying to print global var outside the func and from "Changed" package: 1
trying to print local var outside the block
In case using "use strict" will get this failure while attempting to run the script:
Global symbol "$test1" requires explicit package name at ./check_global.pl line 24.
Execution of ./check_global.pl aborted due to compilation errors.
Just try to use the following program :
#!/usr/local/bin/perl
use feature ':5.10';
#use warnings;
package a;
{
my $b = 100;
our $a = 10;
print "$a \n";
print "$b \n";
}
package b;
#my $b = 200;
#our $a = 20 ;
print "in package b value of my b $a::b \n";
print "in package b value of our a $a::a \n";
Let us think what an interpreter actually is: it's a piece of code that stores values in memory and lets the instructions in a program that it interprets access those values by their names, which are specified inside these instructions. So, the big job of an interpreter is to shape the rules of how we should use the names in those instructions to access the values that the interpreter stores.
On encountering "my", the interpreter creates a lexical variable: a named value that the interpreter can access only while it executes a block, and only from within that syntactic block. On encountering "our", the interpreter makes a lexical alias of a package variable: it binds a name, which the interpreter is supposed from then on to process as a lexical variable's name, until the block is finished, to the value of the package variable with the same name.
The effect is that you can then pretend that you're using a lexical variable and bypass the rules of 'use strict' on full qualification of package variables. Since the interpreter automatically creates package variables when they are first used, the side effect of using "our" may also be that the interpreter creates a package variable as well. In this case, two things are created: a package variable, which the interpreter can access from everywhere, provided it's properly designated as requested by 'use strict' (prepended with the name of its package and two colons), and its lexical alias.
Sources:
http://perldoc.perl.org/functions/our.html
http://perldoc.perl.org/perlsub.html#Private-Variables-via-my()
#!/usr/bin/perl -l
use strict;
# if string below commented out, prints 'lol' , if the string enabled, prints 'eeeeeeeee'
#my $lol = 'eeeeeeeeeee' ;
# no errors or warnings at any case, despite of 'strict'
our $lol = eval {$lol} || 'lol' ;
print $lol;
Related
Why is $var unavailable (out of scope ?) to write when declared with my, if its scope is pretty much package-level ?
package ASDF;
use warnings;
use strict;
use feature 'say';
my $var = 'foo';
format =
#<<<<< #>>>>>
'test : ', $var
.
sub test {
say $var;
write;
}
1;
Called with :
perl -wE 'use ASDF; ASDF::test();'
Produces :
foo
Variable "$var" is not available at ASDF.pm line 16.
Use of uninitialized value $var in formline at ASDF.pm line 10.
test :
It appears otherwise available to say in the same scope ...
Replacing my with our fixes it :
foo
test : foo
Why can't write pick-up on $var correctly ?
Is it a scope issue, or an issue with how Perl's write or format is implemented ?
At the bottom of the Perl format documentation it says:
Lexical variables (declared with "my") are not visible within a format unless the format is declared within the scope of the lexical variable.
Reading that would imply that what you are trying would work, but apparently lexically scoped variables work differently for format and write when called from outside of the package they where declared in. Also, all of the examples in the article use global variables...
This more modern tutorial about format repeats that you might run into trouble if you use lexically scoped variables (variables declared with my) because write picks the variables from the current package and, as stated in the comments of your question, was written in a time when Perl did not have the my keyword or lexical scoping.
The solutions the article offers:
When you are ready to output some data, you use write. This design shows the age of formats since write doesn't take arguments to fill in the pictures. It uses the variables that are in scope.
our( $id, $name, $food, $amount ) = qw( 12 Buster Tuna 1.0 );
write();
Formats are also a bit crufty because you don't pass arguments to write to fill in the pictures. Perl relies on variables with the specified names being in scope. You can use lexical variables, but they have to be in the same scope as the format definition, and they have to be in scope when you call write. It's impractical to do that with lexicals, so the most agile way involves localized package variables:
foreach my $record ( #cats ) {
local( $id, $name, $food ) = #$record;
write( $fh );
}
And also this advice in the wrap-up:
Use localized package variables to set data for the format
So, our and local seem to be the way to go if you want to keep using format and write in modern Perl.
I have working code, but I am trying to understand why it works. I am also trying to learn more about the internals of Perl 5 (perlbrew, perl-5.26.1, Cygwin x64).
I know from perlvar and strict that use strict 'vars' works by setting flags in $^H. Perl then tests accesses to non-:: variables based on those flags. Somehow, both our and use vars mark variables so that they will pass the test. How do they do so?
For example:
perl -E 'package Foo;
use strict "vars";
use vars qw($foo);
say $foo;'
runs fine (although it produces no output). Based on the source for use vars, I tried this, which I thought would have the same effect:
perl -E 'package Foo;
use strict "vars";
my $sym = "Foo::foo"; # <-- These two lines pulled straight
*$sym = \$$sym; # <-- from the source for the vars pragma
say $foo;'
However, it gave me an error: Global symbol "$foo" requires explicit package name. I also tried $sym = "::Foo:foo" in the above, with the same result.
I checked, and $Foo::foo is in the symbol table:
$ perl -E 'package Foo;
use Data::Dumper;
use strict "vars";
my $sym = "Foo::foo";
*$sym = \$$sym;
say Dumper(\%{"Foo::"});' # <-- Foo's symbol table
Output:
$VAR1 = {
'BEGIN' => *Foo::BEGIN,
'Dumper' => *Foo::Dumper,
'foo' => *Foo::foo # <-- yep, it's there
};
What else is use vars doing that I'm missing? Does our do the same, or something different?
Update
Here's an A/B based on melpomene's answer:
Fails Succeeds
------------------------- ----------------------------------
package Foo; package Foo;
use strict "vars"; use strict "vars";
BEGIN {
package Bar;
my $sym="Foo::foo"; my $sym = "Foo::foo";
*$sym = \$$sym; *$sym = \$$sym;
}
say $foo; say $foo;
use strict 'vars' works by setting flags in $^H.
Yes, but that's an implementation detail. $^H exposes some internal interpreter state bits, but you're not supposed to touch it in normal code.
Somehow, both our and use vars mark variables so that they will pass the test. How do they do so?
This is also considered an implementation detail.
However, we can peek a bit under the hood. strict "vars" complains about undeclared variables (at compile time).
There is a hardcoded list of variables that are exempt from this check; it includes all punctuation variables (e.g. $/, $_, etc. along with $a and $b (used by sort)).
All lexically (i.e. locally) declared variables also pass strict; this is how my, our, and state work. (For our purposes local is not a declaration and does not create local variables; local temporarily changes the value of an existing variable.)
The third exception is variables exported from modules. Using global variables as part of your module interface is generally considered to be a bad idea, but some older modules still do it. English also exports variables because that's its whole point, so we'll use it as an example:
use strict;
use English qw($INPUT_RECORD_SEPARATOR);
$INPUT_RECORD_SEPARATOR = ""; # <--
my $paragraph = readline STDIN;
The line marked <-- does not throw an error because Perl remembers which variables were imported from a module.
What does "exporting" actually mean? It just means aliasing a symbol across package boundaries:
*main::foo = \$Some::Module::foo; # now $main::foo is an alias for $Some::Module::foo
The curious thing is that as far as the Perl internals are concerned, a variable is "imported" if it has been aliased in some other package. It does not matter what it was aliased to; all that matters is where the aliasing happened. use vars (ab-)uses this detail to bypass strict "vars" by exporting your own variables back at you:
package Some::Package;
use vars qw($foo);
works like
package Some::Package;
BEGIN {
package vars;
*Some::Package::foo = \$Some::Package::foo;
}
# now $foo is an alias to ... itself
The other piece of the puzzle is that use happens at compile time, like BEGIN blocks. Your example fails because your aliasing attempt only happens at runtime, which is too late for strict, and because it doesn't switch to a different package to do the aliasing.
In the end vars is just a module, written in plain Perl. our is different: It is a real keyword and part of the language. It also has different behavior: It effectively creates an alias (to a package variable), but that alias lives in a local scope, not the symbol table.
Consider e.g. the following:
my $foo = 2;
{
our $foo = "hello";
print "foo = $foo; main::foo = $main::foo\n";
}
print "foo = $foo; main::foo = $main::foo\n";
This outputs
foo = hello; main::foo = hello
foo = 2; main::foo = hello
because the inner our $foo declaration shadows the outer $foo in the inner block. Within the block both $foo and $main::foo refer to the same variable; outside $foo refers to the lexical my $foo, which is untouched.
Another difference to use vars:
use strict;
package Foo;
our $x = "hello";
package Bar;
print "$x\n"; # hello
This code works fine because package declarations don't create a new scope. There is only one unit of scoping here (the whole file), and so our $x makes $x refer to $Foo::x for the rest of the file, no matter which package you switch into.
On the other hand:
use strict;
package Foo;
use vars qw($x);
$x = "hello";
package Bar;
print "$x\n";
This code doesn't even compile. The reference to $x in the last line can't be resolved: Perl checks the local scope first, but there are no locally declared $x's. It then checks the current package (Bar) and finds nothing either, and without strict "vars" it would have automatically created $Bar::x for you, but with strict "vars" enabled this is simply an error. $Foo::x is irrelevant and never checked.
Trying to understand scope resolution operator.
$a = 5;
foo();
print "Out a = $a\n";
sub foo() {
local $a = 10;
bar();
}
sub bar() {
print "Inside a = $a\n";
print "Global a = $::a\n";
}
Output from this program is :
Inside a = 10
Global a = 10
Out a = 5
I would have expected value of '$::a' to come out as '5' instead of 10. I thought that is what scope resolution operator do. Getting scoped values. In this case, no scope is given, so global value. Please correct me if there is any tweak.
What should I write to get the global value of 'a' inside bar subroutine?
You are misunderstanding ::. Perl doesn't really have global variables (leaving aside certain special identifier names); it has package variables. That is, every global variable belongs to a package. If your code has no package statement, that package is main, so $a is the same as $main::a. And having nothing before the :: is shorthand for main, so $::a is also $main::a.
If you do have a package declaration, package variables used within its scope will be contained in that package unless qualified with ::.
local gives a package variable or hash or array element a temporary value and saves the previous value to be restored when the innermost scope is left.
There is no way to access that saved value from within the scope of the local.
The opposite of global/package variables are lexical variables. You almost always will want to use lexical variables (declared with my), not package variables. Even when you do use package variables, you will hardly ever want to change their value with local. So a good case for using local is going to be truly rare.
Well, first off - don't use $a - single letter variable names are generally nasty, and that goes double for when it's used by sort.
Secondly local doesn't do what you think it does. It even says in the man page:
You really probably want to be using my instead, because local isn't what most people think of as "local". See Private Variables via my() in perlsub for details.
A local modifies the listed variables to be local to the enclosing block, file, or eval. If more than one value is listed, the list must be placed in parentheses. See Temporary Values via local() in perlsub for details, including issues with tied arrays and hashes.
So you probably want to use my, but... actually, more likely, you probably just want to not do that, and don't use globals at all.
#!/usr/bin/env perl
use strict;
use warnings;
our $number = 5;
foo();
print "Out number = $number\n";
sub foo {
my $number = 10;
print "Inside foo: $number\n";
print "Global foo $::number\n";
bar();
}
sub bar {
print "Inside bar = $number\n";
print "Global $::number\n";
}
As you can see - $number is lexically scoped to be "within foo" and doesn't persist into b.
Inside foo: 10
Global foo = 5
Inside a = 5
Global a = 5
Out number = 5
Thirdly - don't use prototypes on your subs. They don't do what you think they do.
I have read many posts in Stackoverflow and in Google which tell that local does not create a variable, instead it works on the existing ones.
I have a small piece of code below and I wonder how local is working when there is no such variable already created.
#use strict;
#use warnings;
&func;
sub func{
local $temp = 20;
print $temp;
}
This I wrote just to understand the concept and I am relatively new to Perl.
Unless you declare a variable with my, variables without a full package specification go into the current package. Here's how you might see variables used for the first time and what they would be:
my $temp; # a scoped, lexical variable that does not live in any package
state $temp; # a persistent lexical variable
our $temp; # a package variable in the current package, declared
$temp; # a package variable in the current package
$main::temp # a package variable in main
$Foo::Bar::temp # a package variable in Foo::Bar
local $temp # a package variable in the current package, with a dynamically-scoped (temporary) value
The local sets the scope of a package variable. When you declare this "dynamic" scope, Perl uses the temporary value you set until the end of the scope. As with other package variables, Perl creates them when you first use them. That you might use it first with local in front doesn't affect that.
Many people who tried to answer your question immediately nagged you about strict. This is a programming aid that helps you not mistype a variable name by forcing you to declare all variables you intend to use. When you use a variable name you haven't declared, it stops the compilation of your program. You can do that with the vars pragma, my, state, or our:
use vars qw($temp);
our $temp;
my $temp;
state $temp;
local isn't part of that, as you've seen. Why? Because that's just how it is. I'd like it more if it were different.
strict won't complain if you use the full package specification, such as $Foo::Bar::temp. You can mistype all of those without ever noticing.
I mostly reserve my use of local for Perl's special variables, which you don't have to declare. If I want to use $_ in a subroutine, perhaps to use the operators that use $_ by default, I'll probably start that with local $_:
sub something {
local $_ = shift #_;
s/.../.../;
tr/.../.../;
...;
}
I probably use local more often with the input record separator so I can use different line endings without affecting might have come before:
my $data = do { local $/; <FILE> };
Those work because there's an implicit first use of those variables that you haven't seen.
Otherwise, I probably want to make variables private to its subroutine so nothing outside the subroutine can see it. In that case, I don't want a package variable that the rest of the program can read or write. That's the job for my variables:
sub something {
my $temp = ...;
}
The trick of programming is to limit what can happen to exactly what you want. If the rest of your program shouldn't be able to see or change the variable, my is the way to go.
I explain this is Learning Perl and write about the details of the package variables in Mastering Perl.
local does not create a variable instead works on the existing ones. but i have a small piece of code below and i wonder how local is working when there is no such variable already created.
Lets make a few steps, and let the perl do some diagnostics,
perl -wE 'local $temp =3'
Name "main::temp" used only once: possible typo at -e line 1.
So local $temp alters $main::temp which is package variable and
perl -wE 'local $main::temp =3'
Name "main::temp" used only once: possible typo at -e line 1.
gives the same warning. So we created a new package variable which is localized.
What does this mean? It means that unlike our $temp it keeps the value of package ('global') variable $temp until it exits enclosing block at which point it restores value to previous value.
A few more tests,
perl -MData::Dumper -E 'say Dumper [exists $main::{t}, ${$main::{t}}]'
$VAR1 = [
'', # `$main::t` is NOT created in main package
undef # retrieving value of `$main::t` thus returns undef
];
perl -MData::Dumper -E '{our $t=7} say Dumper [exists $main::{t}, ${$main::{t}}]'
$VAR1 = [
1, # `$main::t` is created in main package
7 # value of `$main::t`
];
and finally,
perl -MData::Dumper -E '{local $t=7} say Dumper [exists $main::{t}, ${$main::{t}}]'
$VAR1 = [
1, # `$main::t` is *CREATED* in main package
undef # value of `$main::t` reverts to undef at exit of enclosing block
];
local does not create a variable. Simply mentioning $temp is creating the variable. It is created when as soon as it is first encountered, whether at compile-time or at run-time.
$ perl -E'
$foo;
${"bar"};
BEGIN { say $::{foo} && *{ $::{foo} }{SCALAR} ? "exists" : "doesn'\''t exist"; }
BEGIN { say $::{bar} && *{ $::{bar} }{SCALAR} ? "exists" : "doesn'\''t exist"; }
BEGIN { say $::{baz} && *{ $::{baz} }{SCALAR} ? "exists" : "doesn'\''t exist"; }
say $::{foo} && *{ $::{foo} }{SCALAR} ? "exists" : "doesn'\''t exist";
say $::{bar} && *{ $::{bar} }{SCALAR} ? "exists" : "doesn'\''t exist";
say $::{baz} && *{ $::{baz} }{SCALAR} ? "exists" : "doesn'\''t exist";
'
exists # $foo exists at compile-time
doesn't exist # $bar doesn't exist at compile-time
doesn't exist # $baz doesn't exist at compile-time
exists # $foo exists at run-time
exists # $bar exists at run-time
doesn't exist # $baz doesn't exist at run-time
Having variables created simply by naming them makes it hard to spot typos. We use use strict; because it prevents that.
local only has a run-time effect. local temporarily backs up the value of $temp in a way that causes Perl to restore it when the lexical scope is exited.
$ perl -E'
sub f { say $temp; }
$temp = 123;
f();
{
local $temp = 456;
f();
}
f();
'
123
456
123
You forgot to use use strict. If you do not use strict the global package variable $temp will be used.. See http://perlmaven.com/global-symbol-requires-explicit-package-name.
Package variables are always global. They have a name and a package qualifier. You can omit the package qualifier, in which case Perl uses a default, which you can set with the package declaration.
To avoid using global variables by accident, add use strict 'vars' to your program.
From the documentation:
use strict vars: This generates a compile-time error if you access a variable that was
neither explicitly declared (using any of my, our, state, or use vars
) nor fully qualified. (Because this is to avoid variable suicide
problems and subtle dynamic scoping issues, a merely local variable
isn't good enough.)
Without use strict -- specifically use strict 'vars', which is a subset -- just mentioning a variable creates it in the current package. There is no need even for local, and your code can be written like this
sub func{
$temp = 20;
print $temp;
}
func();
output
20
That is one reason why use strict is so important, and it is dangerous to omit it. Without it you have no protection against misspelling variables and silently breaking your program
I am having few doubts about the local/our scope in Perl. I read a lot of documentation, but I am still in confusion is there. Following are the confusions
What is local scope?
what I read is -> local copies the value of global variable, change the value, user will use it and outside the block it will retain the global value
Confusion -> my does the same thing. Only benefit I see is that some variables like $package::var cannot be declared with my scope but can be declared with local scope. What else for local
What is "global" variable?
What I read is -> Its scope is within the package. Basically we put the global variable in #EXPORT array and use it or append the namespace with it to use in other packages.
I doubt -> Again if we declare variable with my scope in main only then we can access the variable throughout the package. Is that right? Is it possible to add the my scoped variables in #EXPORT array and use it in another packages?
I think global variables are declared with our keyword. Is there any other way to do so?
This question may look repetitive, but I am confused.
In terms of scoping, there are three kinds of variables in Perl.
Lexical variables are lexically scoped, which means they are only visible in the current lexical scope (basically file or block).
Package variables, on the other hand, can be used using their qualified form (e.g. $Foo::x) from anywhere in the interpreter, and they can be used without qualification by any code that shares the variable's package.
Certain package variables are visible without qualification anywhere in the interpreter. These include punctuation vars and a few named vars such as #ARGV and STDOUT. For example, $x refers to $Foo::x when in package Foo and $Bar::x when in package Bar (assuming no lexical var named $x is in scope), but $_ always refers to $::_.
Variables are destroyed when they are no longer referenced.
Lexical variables are usually destroyed when the lexical scope is exited.
Package variables are usually destroyed when the program exits.
Here are ways to create variable.
my and state create a lexical variable.
our creates a lexical variable that is aliased to the variable of the same name in the current package. In other words, our $x; is equivalent to my \$x = \$Foo::x; when in package Foo.
Package variables are created on use.
local doesn't create any variables. It simply backs up a variable until the current lexical scope is destroyed. It is restored from its backed-up value at that point.
my does the same thing.
No. local does not change the scope of a variable. While a lexical variable is only visible in a lexical scope, a localized package variable is still visible across the entire interpreter.
$x = 123;
sub foo { print "$x\n"; }
{ local $x = 456; foo(); } # 456
foo(); # 123
$x = 123;
sub foo { print "$x\n"; }
{ my $x = 456; foo(); } # 123
foo(); # 123
What else for local
local is primarily used to approximate the functionality of my for variables that cannot otherwise be declared lexically.
Historically, that was all variables. Since 5.6, only punctuation variables cannot be declared lexically.
What is "global" variable?
A global variable is a variable that can seen globally.
All package variables can be seen by any code in the interpreter, so they're all global.
Or are they? To see them from other packages, you need to qualify them. Are $x and $Foo::x the same variable?
To some, global variables refers to the set of package variables you can use unqualified. It means that package changes the set of global variables. And since the package directive is usually used on a file-basis, that means file-level lexicals are also effectively global by this definition. And they are indeed called that sometimes.
But if the package changes the set of variables that are global, then they're not really global, are they? So think some people, which only consider punctuation variables (e.g. $_) and the few named variables that can be used unqualified from anywhere (*::STDOUT) to be global.
In short, it's a pretty useless term.
Is it possible to add the my scoped variables in #EXPORT array and use it in another packages?
No. #EXPORT is used by Exporter. Exporter would not be able to find anything but package symbols (since files are compiled in fresh lexical scopes), so #EXPORT must only contain package symbols.
There are two kinds of variables, lexically scoped and globally scoped.
In Perl before version 5, there was only globally scoped. These variables are the package variables. These variables are available everywhere in the program if you use the package prefix.
The local keyword was introduced to provide a way to alter the value of one of these package global variables inside a limited scope, such as inside one subroutine. It will save the old value on a stack when entering the scope with the local statement, and upon exiting, it will restore the old value. These are still package globals, which means that they are still available everywhere. If you are inside a scope with a local variable, and you call a subroutine, that variable is still visible inside that subroutine.
The my keyword was introduced in version 5, and provides lexically scoped variables. These variables only exist inside the scope where they are declared. This means that if you call a subroutine, that my variable is not visible. Upon exiting a scope, the my variables simply go away. You should prefer to use my variables when possible, because you do not want your variables to be visible inside subroutines that you call. You cannot use these type of variables in the #EXPORT list because these variables are not visible outside of their scope.
Finally, the our keyword is a combination of both, in that it gives you a variable that is a package global, but that variable is lexically scoped. This means it will be available anywhere in the program, but at the end of the enclosing block, you cannot refer to that variable any more.
Here's what I found out about variable scopes:
my declarations are pretty clear and straightforward if used inside blocks. If used in main outside any block, they are a bit different though, meaning that a my variable declared outside a block is visible even inside functions called from anywhere inside the same file as long as these functions are defined within the same file. If declared inside a block, though, they are not visible to functions even if called from the same block. All my variables seem to live on the stack. And: you cannot localize them with local.
our variables live on the heap. Even if you have a my variable by the same name, the our variable can still be accessed through ${'var'}, which looks up a variable of that name in the symbol table and dereferences it. my variables, on the other hand, have not symbol table entries.
local variables seem to me like a relic from former Perl versions. They are just re-assignments to global (our) variables with block scope and resume their former values after the block terminates. I can see no real sense in using them.
My little program below shows all this, and it shows how badly a declared() test is missing, beyond the well-known defined() test, to identify undeclared variables as such.
#!/usr/bin/perl
use strict;
### This is about variable scoping with my, our and local
my $fsv = "file scope"; # visible for all code in this file
our $gsv = "global scope"; # not different from my $fsv, except in packages
our $lsv = "global"; # global scope, but localized in subsequent block
{
my $bsv = "lex scope"; # visible only inside this block, not even in subs called from here
$gsv = "visible everywhere";
local $lsv = "global, but localized val";
print "This is variable \$bsv with value $bsv inside block\n";
print "This is variable \$fsv with value $fsv inside block\n";
print "This is variable \$lsv with value $lsv inside block\n\n";
print_vars("calledfromblock");
}
print_vars("calledfromoutside");
no strict 'vars'; # needed if testing variable for declaredness rather than definedness
if ( defined $bsv ) {
print "\$bsv as defined outside braces: $bsv\n"
} else {
print "\$bsv not defined outside braces\n";
}
print "This is variable \$lsv with value $lsv outside block\n";
# use strict 'vars'; # no strict 'vars' effective even in sub print_vars unless switched back on
sub print_vars
{
my $whence = shift;
my $gsv = "my variable";
no strict 'refs'; # needed to access the global var $gsv using ${'gsv'} despite the my declaration
if ( $whence eq "calledfromblock" ) {
print "\t print_vars called from within the block:\n";
( defined $bsv ) ? print "\$bsv is $bsv inside sub\n" : print "\$bsv not defined inside sub\n";
( defined $fsv ) ? print "\$fsv is $fsv inside sub\n" : print "\$fsv not defined inside sub\n";
( defined ${'gsv'} ) ? print "\$gsv is ${'gsv'} inside sub\n" : print "\$gsv not defined inside sub\n";
( defined ${'lsv'} ) ? print "\$lsv is ${'lsv'} inside sub\n" : print "\$lsv not defined inside sub\n";
} else {
print "\t print_vars called from outside the block:\n";
( defined $bsv ) ? print "\$bsv is $bsv inside sub\n" : print "\$bsv not defined inside sub\n";
( defined $fsv ) ? print "\$fsv is $fsv inside sub\n" : print "\$fsv not defined inside sub\n";
( defined $gsv ) ? print "\$gsv is $gsv inside sub\n" : print "\$gsv not defined inside sub\n";
( defined $lsv ) ? print "\$lsv is $lsv inside sub\n" : print "\$lsv not defined inside sub\n";
}
print "\n";
}
###Example 1:
sub mess_with_foo {
$foo=0;
}
sub myfunc {
my $foo=20;
mess_with_foo();
print $foo;
}
myfunc();
###Example 2:
sub mess_with_foo {
$foo=0;
}
sub myfunc {
local $foo=20;
mess_with_foo();
print $foo;
}
myfunc();
Example 1 prints 20 because mess_with_foo() could not see my $foo. It could not change it. my $foo can only be seen in its scope of myfunc().
Example 2 prints 0 because mess_with_foo() can see my $foo and change it. local $foo can be seen in its scope of myfunc() AND in the scope of any function called from within its scope of myfunc().
That's the only difference. Neither my $foo nor local $foo will be seen outside of their scope of myfunc().