Wordsmyth's Corner

Perl Primer - Chapter 7 - Classes

by Linda Naughton

Topics
Previous Chapter Next Chapter


Packages versus Modules versus Classes

In the simple case, these terms are almost interchangeable.
Class = Package
Module = A Package defined in a file of the same name.
Object = Instance of a Class.
   Class: LogMgr
   Package: LogMgr
   Module: LogMgr
   File: LogMgr.pm

Using Modules

Just use the "use" statement.
    use GetOpt::Long;
    use LogMgr;
It's kinda like a #include in C.

Instantiating Objects

"new" operator, like in C++
   my $LogMgr = new LogMgr(LOG_FILE);
   if (!defined($LogMgr))
      {
      die "LogMgr failed to initialize.\n";
      }

Calling Object Methods

Dereference using the arrow operator.
   $ConfigMgr->readConfigFile($configFilename);
All object methods receive a reference to the current object (the "self" reference, usually dubbed selfP in the code) as their first parameter.
    sub readConfigFile
    {
    my ($selfP, $filename) = @_;
    }
This is true even for the constructor, even though the object hasn't been created yet. For the CTOR, the first parameter is garbage.
   sub new
   {
   my ($garbageP) = @_;
   }

The Implicit Hash

Each object has its own internal hash. This is where member variables are traditionally stored. The name of the member var is used as a key into the hash.
    sub setConfigFile
    {
    my ($selfP, $filename) = @_;
    $selfP->{"m_configFileName"} = $filename;
    }
To avoid typos, the coding guidelines say to create a constant for each of the member variable name keys.
    use constant M_CONFIG_FILENAME => 'm_configFileName';

    sub setConfigFile
    {
    my ($selfP, $filename) = @_;
    $selfP->{M_CONFIG_FILENAME} = $filename;
    }

Implementing a Package

Define the package.
   package TestPackage;
Define constants for member variable keys.

Define a constructor.

    sub new
    {
    my ($garbageP) = @_;
    my $selfP = {};
    bless $selfP;
    return $selfP;
    }
Define other methods (no specification for public/private).
Just like other subroutines, only the object reference is passed as the first parameter.
All Perl packages must end with a 1 (a pseudo return value).
    # Indicate success from this package.
    1;

TRY IT: Test Package
Previous Chapter Next Chapter