What are Packages in Perl?


The package statement in Perl switches the current naming context to a specified namespace (symbol table). Thus −

  • A package is a collection of code which lives in its own namespace.
  • A namespace is a named collection of unique variable names (also called a symbol table).
  • Namespaces prevent variable name collisions between packages.
  • Packages enable the construction of modules which, when used, won't clobber variables and functions outside of the modules's own namespace.
  • The package stays in effect until either another package statement is invoked, or until the end of the current block or file.
  • You can explicitly refer to variables within a package using the :: package qualifier.

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

Example

 Live Demo

#!/usr/bin/perl

# This is main package
$i = 1;
print "Package name : " , __PACKAGE__ , " $i\n";
package Foo;

# This is Foo package
$i = 10;
print "Package name : " , __PACKAGE__ , " $i\n";
package main;

# This is again main package
$i = 100;
print "Package name : " , __PACKAGE__ , " $i\n";
print "Package name : " , __PACKAGE__ , " $Foo::i\n";
1;

Output

When the above code is executed, it produces the following result −

Package name : main 1
Package name : Foo 10
Package name : main 100
Package name : main 10

Updated on: 02-Dec-2019

170 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements