Current Issue


Table of contents

CD-ROM

Sys Admin and The Perl Journal CD-ROM version 12.0

Version 12.0 delivers every issue of Sys Admin from 1992 through 2006 and every
issue of The Perl Journal from 1996-2002 in one convenient CD-ROM!

Order now!

Sys Admin Magazine > Archives > 2004 > May 2004

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).



MarketPlace

Build IT Knowledge with Current & Trusted Content
Helps Employees Develop & Hone New Technical Programming Skills. Sign Up & Get Full Access.

Villanova University Six Sigma & IT Certificate Programs
100% Online programs in Six Sigma, IS Security, CISSP Prep, Business Analysis, Proj. Mgmt. and more!

Workflow Enabled Help Desk & IT Service Management
Automate service desk activities and integrate processes across IT. Learn more here.

WinDev 11 - Powerful IDE
Develop 10 times faster ! ALM, IDE, .Net, RAD, 5GL, Database, 5GL, 64-bit, etc. Free Express version

Wanna see your ad here?