Introduction to Perl Packages
Perl has a feature that allows you to package sets of code into its own package. You use packages to group subroutines so that these can be re-useable or to "isolate" variables used in a subroutine from other subroutines. This isolation of variables is one of the features to implement object oriented programming in Perl.
What is so Useful about Packages?
You can define packages either within your script or a module (.PM) files. If you look at your lib or site/libdirectories in your Perl distribution, you will see a lot of .PM files.
Packages are defined using the package statement. All scripts are assigned to the main package. So if your script does not have a package statement, it is assigned to the main package. A simple statement such as the one below is considered, by default to be in the main package.
is the same as saying:
The Main Package
A package occupies a
namespace. All variables in Perl are managed using the
Symbol Table. The symbol table is a hash whose name is the name of the package - suffixed by the
::string. So for the main package, the symbol table is
%main::. If we have a script like this:
the variable defined as
$aVarcan also be referenced as
Let us say that you define another package with your main package. We will call it the street package. The code will look like this:
When you run this script, the result will be
As you can see, the
$namevariable in the street package was not affected even if you set a value to a variable with the same name in the main package.
Note also that you can access the
$namevariable in the street package by using the
$street::is the package and
nameis the variable within the package.