Objects
- A class is a package. There's no keyword such as
struct
orclass
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; create (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->new("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 DESTROY { my $obj = shift; print "Ahh ... ", $obj->name(), " is dying\n"; } sub set_salary { my ($obj, $new_salary) = @_; $obj->salary($new_salary); }
- Class methods:
Employee->print(); # 1. "Arrow notation" used for class method new Employee (); # 2. Class method using "Indirect notation".
These two class methods must expect the package name as the first parameter, followed by the rest of the arguments.
- Instance methods. There are two ways of invoking methods on an object:
$emp->promote(); promote $obj;