Advanced Perl Programming

Advanced Perl ProgrammingSearch this book
Previous: B.4 ModulesAppendix B
Syntax Summary
Next: B.6 Dynamic Behavior

B.5 Objects

Salient points:

  1. 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}


    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;
  2. Using object package:

    use Employee;
    $emp = Employee->new("Ada", 35);
  3. 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) = @_;
  4. 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.

  5. Instance methods. There are two ways of invoking methods on an object:

    promote $obj;

Previous: B.4 ModulesAdvanced Perl ProgrammingNext: B.6 Dynamic Behavior
B.4 ModulesBook IndexB.6 Dynamic Behavior