Perl Packages Modules

The package statement in perl basically switches the current naming context to a specified namespace. Therefore:

  • A package in perl, is basically a collection of code, lives in its own namespace
  • The package in perl, stays until either another package statement is invoked, or until the end of current block/file
  • Packages in perl, enables the construction of the modules which, when used, won't clobber the variables and the functions outside of the own namespace of the module
  • A namespace in perl, is a named collection of unique variable names
  • Namespaces in perl, simply prevent the variable name collisions between the packages
  • You are free to explicitly refer to the variables within the packages simply by using the :: package qualifier

Here is an example, having main and Foo packages in a file. Here, __PACKAGE__, special variable used to print the package name:


# following is the main package

$i = 1; 
print("Package name = " , __PACKAGE__ , " $i\n"); 

package Foo;

# following is the Foo package

$i = 10; 
print("Package name = " , __PACKAGE__ , " $i\n"); 

package main;

# following is again the main package

$i = 100; 
print("Package name = " , __PACKAGE__ , " $i\n"); 
print("Package name = " , __PACKAGE__ ,  " $Foo::i\n"); 


When the above perl code is executed, it will produce the following output:

Package name = main 1
Package name = Foo 10
Package name = main 100
Package name = main 10

Perl Modules

Module in perl, is basically a reusable package defined in the library file whose name is the same as the package's name along with .pm extension. Here is an example:


package Foo;
sub bar
   print "Hello $_[0]\n" 

sub blat
   print "World $_[0]\n" 

Perl Online Test

« Previous Tutorial Next Tutorial »

Like/Share Us on Facebook 😋