In terms of scoping, there are two kinds of variables in Perl.
- Lexical variables are lexically scoped, which means they are only visible in the current lexical scope.
- Package variables are globally scoped, which means they are visible by all code in the interpreter.
Here are ways to create variable.
my
creates 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 $foo;
is the same as alias my $foo = $The::Current::Package::foo;
.
- Global variables are created on use.
local
doesn't create any variables. It simply backs up a variable until the current lexical scope is destroyed.
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 global variable is still visible across the entire interpreter.
$x = 123;
sub foo { print "$x
"; }
{ local $x = 456; foo(); } # 456
foo(); # 123
$x = 123;
sub foo { print "$x
"; }
{ 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 variable that can seen globally, i.e. by any code in the interpreter.
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 global symbols (since files are compiled in fresh lexical scopes), so @EXPORT
must only contain global symbols.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…