Object-Oriented
Perl
In
Perl, modules and object-oriented programming go hand in hand. Not
all modules are written in an object-oriented fashion, but most are.
A couple of definitions are warranted here:
·
An object is simply a referenced thingy that happens to know
which class it
belongs
to.
·
A class is simply a package that happens to provide methods
to deal with objects.
·
A method is simply a subroutine that expects an object
reference (or a package name, for class methods) as its first
argument.
To
create an object (or instance of a class), use the class constructor.
Usually the class constructor will be a function named “new,” but
may be called “Create” for some Win32 modules. For example,
$tri
= new Triangle::Right (side1=>3, side2=>4);
The
constructor takes a list of arguments describing the properties of
the object to be created (see the documentation of the module in
question to determine what these should be) and returns a reference
to the created object.
An
example of a class constructor (internal to the module) is shown
below:
package
critter; # declare the name of the package
sub
new {
my
$class = shift; # Get class name
my
$self = {}; # Initialize the object to nothing
bless
$self, $class; # Declare object to be part of class
$self->_initialize();#
Do other initializations
return
$self;
}
Methods
(subroutines expecting an object reference as their first argument)
may be invoked in two ways:
Packagename->constructor(args)->method_name(args)
Or:
$object
= Packagename->constructor(args);
$object->method_name(args);
Methods
are simply declared subroutines in the package source file.
No comments :
Post a Comment