Perl - Packages
In a Nutshell - CIW Course Section 2, Part B3, Chapter 1
Packages Overview
A package is a namespace, a namespace is a section of code, or space, in which variable names have validity. Ordinarily, a variable has scope throughout the whole script, unless declared with the "me" keyword within a function where it has scope only within the function.
The use of the package keyword allows the creation of a distinct namespace, which can improve the reusability of your code.
The code that comprises the package, is the code following the package keyword until another package keyword is encountered or the end of the file is reached.
package foo;
$myfoo = "What is Foo?";
package bar;
$myfoo = "A Separate Variable";
print("$myfoo\n");
package foo;
print("$myfoo\n");
Script Output
It can be seen that the two instances of $myfoo are distinct, one does not affect the other. The "foo" package appears twice, effectively moving the focus or scope from one namespace to the other.
The term "Foo" appears repeatedly throughout the course manuals and I often wondered about this odd word, so What is Foo?
Symbol Tables
We have seen that each package maintains it's own set of unique variables or symbols. Perl stores these symbols in a symbol table, which is, in fact, a hash.
package foo;
$myfoo = "What is Foo?";
package bar;
$myfoo = "A Separate Variable";
print("$myfoo\n");
print("$foo::myfoo\n");
This script produces an identical output to the previous script but it achieves it in a different way. Rather than switch the scope back to the "foo" package, we have used $foo::myfoo to reference the symbol within the foo package. This is a new way of referencing a hash that we haven't used before.
Nested Packages
A package can contain other packages, further allowing the grouping of related sections of code.
package car;
$myvar = "I am a car";
package car::engine;
$myvar = "I am an internal combustion engine";
package car::gearbox;
$myvar = "I am an automatic gearbox";
package car;
print("$car::gearbox::myvar\n");
The above script demonstrates how to declare the nested packages and shows how to reference the symbol values within a nested package.
Begin and End Blocks
BEGIN and END blocks define blocks of code that will execute as the interpreter starts or ends respectively. It doesn't matter where in your code these appear as the normal execution order is overridden by these keywords:
END { print("three"); }
print("two");
BEGIN { print("one"); }
Output: onetwothree
Your code may contain multiple BEGIN and END blocks in which case, the BEGIN blocks are executed in the order they are defined while the END blocks are executed in the reverse order that they are defined.

