Perl's concept of global variables is quite similar to special variables in CL.
You can “shadow” the value of a global variable with local
:
our $var = 1;
func("before");
{
# a block creates a new scope
local $var = 2;
func("inside");
}
func("after");
sub func { say "@_: $var" }
Output:
before: 1
inside: 2
after: 1
If you local
a value, the new value is visible throughout the whole dynamic scope, i.e. in all functions that are called. The old value is restored once the lexical scope is left by any means (errors, returns, etc). Tail calls do not extend the dynamic scope, but count as scope exit.
Note that global variables have a fully qualified name. From a different package, you would do something like
local $Other::Package::var = 3;
Other::Package::func("from a package far, far away");
This is commonly used to provide configuration for packages with a functional (non-OO) interface. Important examples are
Carp
and
Data::Dumper
.