Variables in Perl are really funny (meaning they could keep your head banging against a wall for hours…). Recently I discovered some facts about variables in Perl that have help to understand much better how they work and why some things actually happen.
In Perl there are two set of variables:
- Package variables
- Lexical variables
Lexical variables (or when local does not really mean local)
Likewise many scripting languages, variables in Perl are created at run-time. There is no need to declare them before use them.
Originally in Perl any variable was global, that means, it was accessible from any other point of the program and its value could also be changed. We may say, its scope was global.
Then Perl hackers thought it would be convenient to add local variables. A local variable, or automatic variable in the C jargon, is a variable which its scope is limited to the block of code from which it was declared (and all its descendants, neither its siblings nor its ancestors). Then, the reserved word local was added to the language in Perl 4.0. Although, local was more like a work-around in fact than a truly mechanism to provide local variables.
Then in Perl 5.0, a new reserved word, my, was added to the language providing a reliable way to handle local variables. The clause my was chosen, first, for giving the idea of privacy and more importantly because local was already being used. local and my coexist since Perl 5.0
The main difference between my and local is that my do create a local variable, whereas local don’t. What local does in the statement local $x, for instance, is first to save the package variable $x in a safe place and replace it with a new value. Later, it would arrange the old value to be restored when control leaves the current block.
|
This prints
B can see the value of lo set by A.
B cannot see the value of m set by A.
In conclusion, always use my never use local.
Package variables (or why my script got broken when I tried to import an external file???)
Whereas global variables are visible within the context of the file they were declared, package variables can be shared among different packages.
Two facts about package variables:
* Package variables are always global.
* Package variables are what you get, by default, if you do not say something else.
A package variable looks like this:
- Package::variable
Usually you leave the package part blank, meaning the current package.
Remember package variables are always global. A variable from other module can always be reference from other module using the package prefix (you should import that external module before, using either the clauses use or require). For instance,
|
This prints
x: 10
Package with the empty name is refer as main. So, putting two and two together, we got that $main::x is the same as $x;
I will deep more on package variables in a coming post, example included.
Further reading: