Packages
CHAPTER 19: PACKAGES
The Problem
- To support abstract data types (objects!!), a language must
provide a mechanism for a set of related subroutines to share
variables and yet NOT allow these variables to be accessible
by other subroutines
- For example, a set of subroutines which implements a queue or a
stack, needs to share some variables which must remain private
to that set of subroutines
- Obviously, global variables do not work here. Nor do variables
created by the local() function, since such variables are local
to the enclosing block and can not be shared
The Solution
- PACKAGES!!
Packages
- A package provides an alternate namespace (symbol table) for
variables (and filehandles, formats, etc.)
- The same variable name in two different packages refers to two
different variables
- The scope of a package declaration extends from the declaration
itself to the end of the enclosing block
The Main Package
- The default package is called main and initially Perl begins
compilation of all variables in the main namespace
- So "global" variables are really variables in the main package
Package Example
- Here is a typical use of a package:
#!/usr/bin/perl
sub add_to_count
{
package Count;
$x = @_;
$count += $x;
print ("Count package: count is $count\n");
}
sub subtract_from_count
{
package Count;
$x = @_;
$count -= $x;
print ("Count package: count is $count\n");
}
$count = 17;
print ("Main package: count is $count\n");
&add_to_count (23);
print ("Main package: count is $count\n");
&subtract_from_count (13);
print ("Main package: count is $count\n");
The results of this program are:
Main package: count is 17
Count package: count is 23
Main package: count is 17
Count package: count is 10
Main package: count is 17
Note that the $count variable in the main package and the $count
in the Count package are two different variables. But since
the two subroutines are in the same Count package they share
access to the Count package $count variable.
More Package Advantages
- No need to use local()
- Can not inadvertently clobber variables outside the package
- No danger of variable suicide in a subroutine
Fully Qualified Variable Name
- You can override the private nature of package variables and
refer to variables in other packages by using a fully qualified
variable name
- The fully qualified name is:
package_name'variable_name
- Ex.
$main'count = 15; # Set the $count variable in the main
# package to 15
$Count'count = 89; # Set the $count variable in the Count
# package to 89. Can do this from
# ANY package!!
Bob Tarr
University of Maryland, Baltimore County
tarr@umbc.edu