Contents / Previous / Next


Packages

Perl provides a mechanism for alternate namespaces to protect packages from stomping on each others variables.

By default, a perl script starts compiling into the package known as "main".

By use of the package declaration, you can switch namespaces.

Example:

#!/usr/bin/perl -w package my_pkg; sub my_print { print "oh me!\n"; } package my_other_pkg; sub my_print { print "oH! That's also me!\n"; } package main; &my_pkg::my_print; &my_other_pkg::my_print;


Perl Modules

A module is a package that is defined in a (library) file of the same name and with the extension ".pm" .

Perl modules are included by saying:

use Module;

or

use Module LIST;

This is exactly equivalent to

BEGIN { require "Module.pm"; import Module; }

or

BEGIN { require "Module.pm"; import Module LIST; }

Modules and packages are searched for in the path defined in the @ISA array.


Perl Classes

Because a class in Perl is really just a package, using package variables to hold class attributes and package subroutines that function as methods.

Example "Person class" stored in Person.pm:

package Person; use strict; ################################################## ## the object constructor (simplistic version) ## ################################################## sub new { my $self = {}; $self->{NAME} = undef; $self->{AGE} = undef; $self->{PEERS} = []; bless($self); # but see below return $self; } ############################################## ## methods to access per-object data ## ## ## ## With args, they set the value. Without ## ## any, they only retrieve it/them. ## ############################################## sub name { my $self = shift; if (@_) { $self->{NAME} = shift } return $self->{NAME}; } sub age { my $self = shift; if (@_) { $self->{AGE} = shift } return $self->{AGE}; } sub peers { my $self = shift; if (@_) { @{ $self->{PEERS} } = @_ } return @{ $self->{PEERS} }; } 1; # so the require or use succeeds In order to manufacture objects, a class needs to have a constructor method. A constructor gives you back not just a regular data type, but a brand-new object in that class.
This magic is taken care of by the bless() function, whose sole purpose is to enable its referent to be used as an object.
While a constructor may be named anything you'd like, most Perl programmers seem to like to call theirs new(). However, new() is not a reserved word, and a class is under no obligation to supply such. Some programmers have also been known to use a function with the same name as the class as the constructor.

...Example "using the person class in a script":

use Person; $him = Person->new(); $him->name("Jason"); $him->age(23); $him->peers( "Norbert", "Rhys", "Phineas" ); push @All_Recs, $him; # save object in array for later printf "%s is %d years old.\n", $him->name, $him->age; print "His peers are: ", join(", ", $him->peers), "\n"; printf "Last rec's name is %s\n", $All_Recs[-1]->name;