<P>First you need to understand what references are in Perl.
See <A HREF="../../lib/Pod/perlref.html">the perlref manpage</A> for that. Second, if you still find the following
reference work too complicated, a tutorial on object-oriented programming
in Perl can be found in <A HREF="../../lib/Pod/perltoot.html">the perltoot manpage</A> and <A HREF="../../lib/Pod/perltootc.html">the perltootc manpage</A>.</P>
<P>If you're still with us, then
here are three very simple definitions that you should find reassuring.</P>
<OL>
<LI>
An object is simply a reference that happens to know which class it
belongs to.
<P></P>
<LI>
A class is simply a package that happens to provide methods to deal
with object references.
<P></P>
<LI>
A method is simply a subroutine that expects an object reference (or
a package name, for class methods) as the first argument.
<P></P></OL>
<P>We'll cover these points now in more depth.</P>
<P>
<H2><A NAME="an object is simply a reference">An Object is Simply a Reference</A></H2>
<P>Unlike say C++, Perl doesn't provide any special syntax for
constructors. A constructor is merely a subroutine that returns a
reference to something ``blessed'' into a class, generally the
class that the subroutine is defined in. Here is a typical
constructor:</P>
<PRE>
package Critter;
sub new { bless {} }</PRE>
<P>That word <CODE>new</CODE> isn't special. You could have written
a construct this way, too:</P>
<PRE>
package Critter;
sub spawn { bless {} }</PRE>
<P>This might even be preferable, because the C++ programmers won't
be tricked into thinking that <CODE>new</CODE> works in Perl as it does in C++.
It doesn't. We recommend that you name your constructors whatever
makes sense in the context of the problem you're solving. For example,
constructors in the Tk extension to Perl are named after the widgets
they create.</P>
<P>One thing that's different about Perl constructors compared with those in
C++ is that in Perl, they have to allocate their own memory. (The other
things is that they don't automatically call overridden base-class
constructors.) The <CODE>{}</CODE> allocates an anonymous hash containing no
key/value pairs, and returns it The <A HREF="../../lib/Pod/perlfunc.html#item_bless"><CODE>bless()</CODE></A> takes that reference and
tells the object it references that it's now a Critter, and returns
the reference. This is for convenience, because the referenced object
itself knows that it has been blessed, and the reference to it could
have been returned directly, like this:</P>
<PRE>
sub new {
my $self = {};
bless $self;
return $self;
}</PRE>
<P>You often see such a thing in more complicated constructors
that wish to call methods in the class as part of the construction:</P>
<PRE>
sub new {
my $self = {};
bless $self;
$self->initialize();
return $self;
}</PRE>
<P>If you care about inheritance (and you should; see
<A HREF="../../lib/Pod/perlmodlib.html#modules: creation, use, and abuse">Modules: Creation, Use, and Abuse in the perlmodlib manpage</A>),
then you want to use the two-arg form of bless
so that your constructors may be inherited:</P>
<PRE>
sub new {
my $class = shift;
my $self = {};
bless $self, $class;
$self->initialize();
return $self;
}</PRE>
<P>Or if you expect people to call not just <CODE>CLASS->new()</CODE> but also
<CODE>$obj->new()</CODE>, then use something like this. The <CODE>initialize()</CODE>
method used will be of whatever $class we blessed the
object into:</P>
<PRE>
sub new {
my $this = shift;
my $class = ref($this) || $this;
my $self = {};
bless $self, $class;
$self->initialize();
return $self;
}</PRE>
<P>Within the class package, the methods will typically deal with the
reference as an ordinary reference. Outside the class package,
the reference is generally treated as an opaque value that may
be accessed only through the class's methods.</P>
<P>Although a constructor can in theory re-bless a referenced object
currently belonging to another class, this is almost certainly going
to get you into trouble. The new class is responsible for all
cleanup later. The previous blessing is forgotten, as an object
may belong to only one class at a time. (Although of course it's
free to inherit methods from many classes.) If you find yourself
having to do this, the parent class is probably misbehaving, though.</P>
<P>A clarification: Perl objects are blessed. References are not. Objects
know which package they belong to. References do not. The <A HREF="../../lib/Pod/perlfunc.html#item_bless"><CODE>bless()</CODE></A>
function uses the reference to find the object. Consider
the following example:</P>
<PRE>
$a = {};
$b = $a;
bless $a, BLAH;
print "\$b is a ", ref($b), "\n";</PRE>
<P>This reports $b as being a BLAH, so obviously <A HREF="../../lib/Pod/perlfunc.html#item_bless"><CODE>bless()</CODE></A>
operated on the object and not on the reference.</P>
<P>
<H2><A NAME="a class is simply a package">A Class is Simply a Package</A></H2>
<P>Unlike say C++, Perl doesn't provide any special syntax for class
definitions. You use a package as a class by putting method
definitions into the class.</P>
<P>There is a special array within each package called @ISA, which says
where else to look for a method if you can't find it in the current
package. This is how Perl implements inheritance. Each element of the
@ISA array is just the name of another package that happens to be a
class package. The classes are searched (depth first) for missing
methods in the order that they occur in @ISA. The classes accessible
through @ISA are known as base classes of the current class.</P>
<P>All classes implicitly inherit from class <CODE>UNIVERSAL</CODE> as their
last base class. Several commonly used methods are automatically
supplied in the UNIVERSAL class; see <A HREF="#default universal methods">Default UNIVERSAL methods</A> for
more details.</P>
<P>If a missing method is found in a base class, it is cached
in the current class for efficiency. Changing @ISA or defining new
subroutines invalidates the cache and causes Perl to do the lookup again.</P>
<P>If neither the current class, its named base classes, nor the UNIVERSAL
class contains the requested method, these three places are searched
all over again, this time looking for a method named AUTOLOAD(). If an
AUTOLOAD is found, this method is called on behalf of the missing method,
setting the package global $AUTOLOAD to be the fully qualified name of
the method that was intended to be called.</P>
<P>If none of that works, Perl finally gives up and complains.</P>
<P>Perl classes do method inheritance only. Data inheritance is left up
to the class itself. By and large, this is not a problem in Perl,
because most classes model the attributes of their object using an
anonymous hash, which serves as its own little namespace to be carved up
by the various classes that might want to do something with the object.
The only problem with this is that you can't sure that you aren't using
a piece of the hash that isn't already used. A reasonable workaround
is to prepend your fieldname in the hash with the package name.</P>
<PRE>
sub bump {
my $self = shift;
$self->{ __PACKAGE__ . ".count"}++;
}</PRE>
<P>
<H2><A NAME="a method is simply a subroutine">A Method is Simply a Subroutine</A></H2>
<P>Unlike say C++, Perl doesn't provide any special syntax for method
definition. (It does provide a little syntax for method invocation
though. More on that later.) A method expects its first argument
to be the object (reference) or package (string) it is being invoked
on. There are two ways of calling methods, which we'll call class
methods and instance methods.</P>
<P>A class method expects a class name as the first argument. It
provides functionality for the class as a whole, not for any
individual object belonging to the class. Constructors are often
class methods, but see <A HREF="../../lib/Pod/perltoot.html">the perltoot manpage</A> and <A HREF="../../lib/Pod/perltootc.html">the perltootc manpage</A> for alternatives.
Many class methods simply ignore their first argument, because they
already know what package they're in and don't care what package
they were invoked via. (These aren't necessarily the same, because
class methods follow the inheritance tree just like ordinary instance
methods.) Another typical use for class methods is to look up an
object by name:</P>
<PRE>
sub find {
my ($class, $name) = @_;
$objtable{$name};
}</PRE>
<P>An instance method expects an object reference as its first argument.
Typically it shifts the first argument into a ``self'' or ``this'' variable,
<P>If you're trying to control where the method search begins <EM>and</EM> you're
executing in the class itself, then you may use the SUPER pseudo class,
which says to start looking in your base class's @ISA list without having
to name it explicitly:</P>
<PRE>
$self->SUPER::display('Height', 'Weight');</PRE>
<P>Please note that the <CODE>SUPER::</CODE> construct is meaningful <EM>only</EM> within the
class.</P>
<P>Sometimes you want to call a method when you don't know the method name
ahead of time. You can use the arrow form, replacing the method name
with a simple scalar variable containing the method name or a
reference to the function.</P>
<PRE>
$method = $fast ? "findfirst" : "findbest";
$fred->$method(@args); # call by name</PRE>
<PRE>
if ($coderef = $fred->can($parent . "::findbest")) {
$self->$coderef(@args); # call by coderef
}</PRE>
<P>
<H2><A NAME="warning">WARNING</A></H2>
<P>While indirect object syntax may well be appealing to English speakers and
to C++ programmers, be not seduced! It suffers from two grave problems.</P>
<P>The first problem is that an indirect object is limited to a name,
a scalar variable, or a block, because it would have to do too much
lookahead otherwise, just like any other postfix dereference in the
language. (These are the same quirky rules as are used for the filehandle
slot in functions like <A HREF="../../lib/Pod/perlfunc.html#item_print"><CODE>print</CODE></A> and <A HREF="../../lib/Pod/perlfunc.html#item_printf"><CODE>printf</CODE></A>.) This can lead to horribly
confusing precedence problems, as in these next two lines:</P>
<PRE>
move $obj->{FIELD}; # probably wrong!
move $ary[$i]; # probably wrong!</PRE>
<P>Those actually parse as the very surprising:</P>
<PRE>
$obj->move->{FIELD}; # Well, lookee here
$ary->move([$i]); # Didn't expect this one, eh?</PRE>
<P>Rather than what you might have expected:</P>
<PRE>
$obj->{FIELD}->move(); # You should be so lucky.
$ary[$i]->move; # Yeah, sure.</PRE>
<P>The left side of ``->'' is not so limited, because it's an infix operator,
not a postfix operator.</P>
<P>As if that weren't bad enough, think about this: Perl must guess <EM>at
compile time</EM> whether <CODE>name</CODE> and <CODE>move</CODE> above are functions or methods.
Usually Perl gets it right, but when it doesn't it, you get a function
call compiled as a method, or vice versa. This can introduce subtle
bugs that are hard to unravel. For example, calling a method <CODE>new</CODE>
in indirect notation--as C++ programmers are so wont to do--can
be miscompiled into a subroutine call if there's already a <CODE>new</CODE>
function in scope. You'd end up calling the current package's <CODE>new</CODE>
as a subroutine, rather than the desired class's method. The compiler
tries to cheat by remembering bareword <A HREF="../../lib/Pod/perlfunc.html#item_require"><CODE>require</CODE></A>s, but the grief if it
messes up just isn't worth the years of debugging it would likely take
you to track such subtle bugs down.</P>
<P>The infix arrow notation using ``<CODE>-></CODE>'' doesn't suffer from either
of these disturbing ambiguities, so we recommend you use it exclusively.</P>
<P>For most purposes, Perl uses a fast and simple, reference-based
garbage collection system. That means there's an extra
dereference going on at some level, so if you haven't built
your Perl executable using your C compiler's <CODE>-O</CODE> flag, performance
will suffer. If you <EM>have</EM> built Perl with <CODE>cc -O</CODE>, then this
probably won't matter.</P>
<P>A more serious concern is that unreachable memory with a non-zero
reference count will not normally get freed. Therefore, this is a bad
idea:</P>
<PRE>
{
my $a;
$a = \$a;
}</PRE>
<P>Even thought $a <EM>should</EM> go away, it can't. When building recursive data
structures, you'll have to break the self-reference yourself explicitly
if you don't care to leak. For example, here's a self-referential
node such as one might use in a sophisticated tree structure:</P>
<PRE>
sub new_node {
my $self = shift;
my $class = ref($self) || $self;
my $node = {};
$node->{LEFT} = $node->{RIGHT} = $node;
$node->{DATA} = [ @_ ];
return bless $node => $class;
}</PRE>
<P>If you create nodes like that, they (currently) won't go away unless you
break their self reference yourself. (In other words, this is not to be
construed as a feature, and you shouldn't depend on it.)</P>
<P>Almost.</P>
<P>When an interpreter thread finally shuts down (usually when your program
exits), then a rather costly but complete mark-and-sweep style of garbage
collection is performed, and everything allocated by that thread gets
destroyed. This is essential to support Perl as an embedded or a
multithreadable language. For example, this program demonstrates Perl's
two-phased garbage collection:</P>
<PRE>
#!/usr/bin/perl
package Subtle;</PRE>
<PRE>
sub new {
my $test;
$test = \$test;
warn "CREATING " . \$test;
return bless \$test;
}</PRE>
<PRE>
sub DESTROY {
my $self = shift;
warn "DESTROYING $self";
}</PRE>
<PRE>
package main;</PRE>
<PRE>
warn "starting program";
{
my $a = Subtle->new;
my $b = Subtle->new;
$$a = 0; # break selfref
warn "leaving block";
}</PRE>
<PRE>
warn "just exited block";
warn "time to die...";
exit;</PRE>
<P>When run as <EM>/tmp/test</EM>, the following output is produced:</P>
<PRE>
starting program at /tmp/test line 18.
CREATING SCALAR(0x8e5b8) at /tmp/test line 7.
CREATING SCALAR(0x8e57c) at /tmp/test line 7.
leaving block at /tmp/test line 23.
DESTROYING Subtle=SCALAR(0x8e5b8) at /tmp/test line 13.
just exited block at /tmp/test line 26.
time to die... at /tmp/test line 27.
DESTROYING Subtle=SCALAR(0x8e57c) during global destruction.</PRE>
<P>Notice that ``global destruction'' bit there? That's the thread
garbage collector reaching the unreachable.</P>
<P>Objects are always destructed, even when regular refs aren't. Objects
are destructed in a separate pass before ordinary refs just to
prevent object destructors from using refs that have been themselves
destructed. Plain refs are only garbage-collected if the destruct level
is greater than 0. You can test the higher levels of global destruction
by setting the PERL_DESTRUCT_LEVEL environment variable, presuming
<CODE>-DDEBUGGING</CODE> was enabled during perl build time.</P>
<P>A more complete garbage collection strategy will be implemented
at a future date.</P>
<P>In the meantime, the best solution is to create a non-recursive container
class that holds a pointer to the self-referential data structure.
Define a DESTROY method for the containing object's class that manually
breaks the circularities in the self-referential structure.</P>
<P>
<HR>
<H1><A NAME="see also">SEE ALSO</A></H1>
<P>A kinder, gentler tutorial on object-oriented programming in Perl
can be found in <A HREF="../../lib/Pod/perltoot.html">the perltoot manpage</A> and <A HREF="../../lib/Pod/perltootc.html">the perltootc manpage</A>. You should also check
out <A HREF="../../lib/Pod/perlbot.html">the perlbot manpage</A> for other object tricks, traps, and tips, as well
as <A HREF="../../lib/Pod/perlmodlib.html">the perlmodlib manpage</A> for some style guides on constructing both modules