Listing 2.4. The Customer module.
package Customer;
=head1 NAME
Customer - Perl module which implements a customer
object.
=head1 SYNOPSIS
use Customer
$cust = New Customer(args);
$cust->dumpcust();
$cust->addstat();
=head1 DESCRIPTION
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 <wmiddlet@adobe.com>
=cut
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";
}
1;
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 Customer.pm module, from Listing 2.4, somewhere in @INC, or pasted into Listing 2.5, for it to work.)