CGI and Perl

Listing 2.4. The Customer module.

package Customer;
 =head1 NAME
 Customer - Perl module which implements a customer
 =head1 SYNOPSIS
     use Customer
     $cust = New Customer(args);
 This module may be used to create a set of customer
 objects, for use within a program which needs an
 implementation of this sort.
 =head1 AUTHOR
 Bill Middleton <>
 sub new {
 my $type = shift;
 my %args = @_;
 my $self = {};
 $self->{`Name'} =
     length($args{`Name'}) ? $args{`Name'} : "No name given";
 $self->{`Vitals'} =
     defined(@{$args{`Vitals'}}) ? $args{`Vitals'} : ["No vitals"];
 bless $self, $type;
 sub addstat{
 my $self = shift;
 my $key = shift;
 my $val = shift;
     $self->{$key} = $val;
 sub dumpcust{
 my $self = shift;
 # Print out the values for the object
 print $self->{Name},"\n";
 print $self->{Phone},"\n";
 print join(` `,@{$self->{Vitals}}),"\n";

Note that this module now provides the explicit means to obtain a reference to itself, by providing the new() method. As previously demonstrated, the new() method usually initializes a reference with some values for the customer's name and vitals, based on the arguments passed in. These variables are also known as instance variables, because they exist for each new object that is created. Because you expect any access to this package to be through the blessed reference, you're not going to export any methods.

Now you can use the blessed reference variable to invoke the methods that are defined in the package safely, with no worries about namespace collisions. You have the added benefit of automatically passing in the instance variables that have been declared within the reference variable, or object, that was returned by the new() method. (Note that you'll need to have the module, from Listing 2.4, somewhere in @INC, or pasted into Listing 2.5, for it to work.)

Listing 2.5. Using the Customer module.

use Customer;# Create a new customer object
 $cust  = Customer->new( `Name' => "Billy T. Kid",
         `Vitals' => ["Age : 10", "Sex : M"] );
 # add a single statistic
 $cust->addstat(`Phone' => `1-203-456-7890');
 # Print out the values for the object

You will probably end up using a combination of the techniques I've discussed to work with modules within your Perl programs and obtain the level of functionality that you want. Each and every module that you use in your Perl programs will be a little bit different, certainly, but once you understand how you can use them, you're on your way to making use of any one of them.