Object-oriented Perl programming is introduced in Chapter 3 and Chapter 4, and used in all the remaining chapters of the book.
There are three main concepts:
A class is a Perl module with a package declaration. The name of the class is the same as the name of the package; the module file also has the same name but with ".pm" (for Perl module) appended.
An object is a reference to a collection of data used by a Perl class, usually but not necessarily, implemented as a hash. An object is marked with the name of its class using bless.
A method is a subroutine in the class.
Arrow notation -> is used in a special way in object-oriented Perl code and has an effect on what arguments are passed to the class methods.
You use a class in your code by saying, for example:
use Goodclass;
You create an object by calling a constructor method in the class, which is usually (but not necessarily) called new, for example:
$goodobject = Goodclass->new( parameter1 => 1, parameter2 => 2);
Note that arguments are usually (but not necessarily) specified using the hash notation key => value, and therefore can be given in any order.
You call other methods in the class by invoking them from a class object. For example you call the method stuff in class Goodclass on a Goodclass object $goodobject, with argument type initialized to the value 'good', and save its output in the array @goodstuff, like so:
@goodstuff = $goodobject->stuff(type => 'good');
The arrow notation causes the called method to insert an additional argument. (In the examples just shown, the methods are the subroutines new and stuff).
The additional argument is the class information that appears to the left of the arrow. So, in these examples, the method new has the argument list:
('Goodclass', parameter1=1, parameter2=2)
The method stuff has the argument list:
($goodobject, type='good')
The details of how arguments are passed to methods are important to know only if you are writing a class, not if you are using one. If you simply use a class, you only have to know how to call the class methods using the arrow notation as just shown.
Inheritance is a technique with which you can write a new class that uses definitions from an already existing class.
AUTOLOAD is a subroutine that handles calls to undefined methods, and DESTROY is a subroutine that handles cleanup when a class object goes out of scope.
In addition to object methods that operate on individual class objects, you can also define class methods that have access to information about multiple class objects?for example, a count of how many objects have been created.
A great deal of the utility of existing Perl code is available only in class modules. In this book I use some of the important and well-known modules including DBI, CGI, GD and GD::Graph, and the Bioperl collection of modules. Almost all modules are available at http://www.CPAN.org.