Constructing
Objects
Randal L. Schwartz
To construct an object in Perl, you must select a valid package name for the
object's class, populate that package with subroutines to define the methods,
set the value of @ISA within that package to define the base (parent)
classes for that class, and then create a blessed reference. For example, we
can make widgets that know how to say their names and take on new names with
the following code (I'll describe $self in a moment):
package Widget;
sub display {
my $self = shift;
print $self->{name}, "\n";
}
sub rename {
my $self = shift;
$self->{name} = shift;
$self;
}
A constructed object compatible with this definition must be a hashref with at
least a key of name holding the name of the object. We can construct such
a hashref like so:
my $dog = { name => 'Spot' };
bless $dog, 'Widget';
The bless operation puts a little post-it note on the hash data structure
(not the reference!) that says, "I belong to Widget". Now, we can invoke the methods
like so:
$dog->display; # prints "Spot\n"
$dog->rename("Fido");
$dog->display; # prints "Fido\n"
How does this work? To execute the rename call, for example, Perl constructs
an argument list consisting of the object variable ($dog) plus any arguments
given to the method, resulting in:
($dog, "Fido")
Next, Perl looks for a subroutine in the package given by the post-it note (the
object's class) named the same as the method. The subroutine Widget::rename
gets invoked, and the first argument ends up in $self. The second argument
is assigned as an element of the hash, and finally the subroutine returns $self
(not a requirement, but handy for other operations).
|