Wednesday, April 30, 2014

Perl Packages

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.

print "hello, world\n";

is the same as saying:
package main;
print "hello, world\n";

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:

$aVar = Hello, World\n";
print $aVar;
print $main::aVar;

the variable defined as $aVar can also be referenced as$main::aVar.

Another Package

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:
package street; {
    $name = "Pembroke Street";
    print "From street: $name\n";
package main; {
    $name = "Philip Yuson";
    print "From main: $name\n";
    print "From main using street: $street::name\n";

When you run this script, the result will be
From street: Pembroke Street
From main: Philip Yuson
From main using street: Pembroke Street

As you can see, the $name variable 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 $name variable in the street package by using the $street::name variable. 

Remember: $street:: is the package and name is the variable within the package.

No comments:

Post a Comment