Wednesday, April 22, 2009

Perl Objects

Perl Objects

What is an object in Perl?

An object is a reference to an item (anything that can be referenced by a reference) that has been blessed.

An object is created by first creating a reference and then using the bless function to bless the referenced item with a package name.

For example:

$reference = {};  # here a reference to a hash but it could be to anything

bless $reference, "Some::Package::name";

The bless function requires a reference as an argument but it modifies the referenced item rather than the reference itself. It sets a flag in the referenced item that indicates that the item is an object and it records the package name as an attribute of the item. With this done, any reference to the item can be used with the arrow operator (a.k.a. dereference operator) for method invocation.

It is the facility of method invocation that makes objects different from other variables.

Method invocation is a means of calling a subroutine. It differs from regular subroutine invocation in two respects:

  1. the package name with which the referenced item was blessed is passed as the first argument to the subroutine, followed by any explicit arguments; and
  2. a runtime lookup of the method name is performed to determine the subroutine to be called.

For example:

$ref->method($arg1, $arg2);

$ref->Package::method($arg1,$arg2);

The method name may be unqualified or qualified with a package name. If it is unqualified, lookup of the subroutine begins in the package with which the referenced item was blessed. If the method name is fully qualified, lookup begins in the specified package, regardless of the package with which the referenced item was blessed.

If the package has a subroutine with the same name as the method name then this subroutine is called.

If the package does not have a subroutine with the same name as the method name then lookup is repeated in each package in the list (@ISA, 'UNIVERSAL'). The @ISA array is a package global and 'UNIVERSAL' is a package that is part of the Perl core distribution which defines several basic methods. As each package may have its own @ISA array, a depth first search of these arrays is performed.

If no matching subroutine is found after this search then the search is repeated but searching for AUTOLOAD rather than the named method and if an AUTOLOAD subroutine is found then it is invoked for the method.

These mechanisms are simple, but the ramifications and possibilities are not.

Because methods are resolved to subroutines at runtime (a.k.a. dynamically), interesting things can be done. Sometimes these are interesting in the sense of wonderful, amazing, powerful and good, but sometimes they are interesting in the sense of the curse: may you live in interesting times. 

No comments:

Labels