August 1997
Intermediate to advanced
432 pages
12h 19m
English
Salient points:
A class is a package. There’s no keyword such as
struct or class to define
layout of object.
You choose object representation — object layout is not dictated by you.
No special syntax for constructor. You choose the name of the subroutine that is going to allocate the object and return a blessed or typed reference to that object.
Creating an OO package — Method 1 (see also #19).
The C++ class:
class Employee {
String _name; int _age; double _salary;
Employee (String n, int age) : _name(n), _age(age), _salary(0) {}
~Employee {printf ("Ahh ... %s is dying\n", _name)}
set_salary (double new_salary) { this->_salary = new_salary}
};becomes:
package Employee;
sub create { # Allocator and Initializer
my ($pkg, $name, $age) = @_;
# Allocate anon hash, bless it, return it.
return (bless {name => $name, age=> $age, salary=>0}, $pkg);
}
sub DESTROY { # destructor (like Java's finalize)
my $obj = shift;
print "Ahh ... ", $obj->{name}, " is dying\n";
}
sub set_salary {
my ($obj, $new_salary) = @_;
$obj->{salary} = $new_salary; # Remember: $obj is ref-to-hash
return $new_salary;
}Using object package:
use Employee;
$emp = Employee->create("Ada", 35);
$emp->set_salary(1000);Creating OO package — Method 2 (see also #17). Inherit from ObjectTemplate, use the
attributes method to declare attribute names, and obtain the
constructor new and attribute accessor functions
for free:
package Employee; use ObjectTemplate; @ISA = ("ObjectTemplate"); attributes("name", "age", "salary"); sub ...Read now
Unlock full access