Plan 9 from Bell Labs’s /usr/web/sources/contrib/gabidiaz/root/sys/man/1perl/perlobj

Copyright © 2021 Plan 9 Foundation.
Distributed under the MIT License.
Download the Plan 9 distribution.


.\" Automatically generated by Pod::Man v1.34, Pod::Parser v1.13
.\"
.\" Standard preamble:
.\" ========================================================================
.de Sh \" Subsection heading
.br
.if t .Sp
.ne 5
.PP
\fB\\$1\fR
.PP
..
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Vb \" Begin verbatim text
.ft CW
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" Set up some character translations and predefined strings.  \*(-- will
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
.\" double quote, and \*(R" will give a right double quote.  | will give a
.\" real vertical bar.  \*(C+ will give a nicer C++.  Capital omega is used to
.\" do unbreakable dashes and therefore won't be available.  \*(C` and \*(C'
.\" expand to `' in nroff, nothing in troff, for use with C<>.
.tr \(*W-|\(bv\*(Tr
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
.ie n \{\
.    ds -- \(*W-
.    ds PI pi
.    if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
.    if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\"  diablo 12 pitch
.    ds L" ""
.    ds R" ""
.    ds C` ""
.    ds C' ""
'br\}
.el\{\
.    ds -- \|\(em\|
.    ds PI \(*p
.    ds L" ``
.    ds R" ''
'br\}
.\"
.\" If the F register is turned on, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
.\" entries marked with X<> in POD.  Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.if \nF \{\
.    de IX
.    tm Index:\\$1\t\\n%\t"\\$2"
..
.    nr % 0
.    rr F
.\}
.\"
.\" For nroff, turn off justification.  Always turn off hyphenation; it makes
.\" way too many mistakes in technical documents.
.hy 0
.if n .na
.\"
.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
.\" Fear.  Run.  Save yourself.  No user-serviceable parts.
.    \" fudge factors for nroff and troff
.if n \{\
.    ds #H 0
.    ds #V .8m
.    ds #F .3m
.    ds #[ \f1
.    ds #] \fP
.\}
.if t \{\
.    ds #H ((1u-(\\\\n(.fu%2u))*.13m)
.    ds #V .6m
.    ds #F 0
.    ds #[ \&
.    ds #] \&
.\}
.    \" simple accents for nroff and troff
.if n \{\
.    ds ' \&
.    ds ` \&
.    ds ^ \&
.    ds , \&
.    ds ~ ~
.    ds /
.\}
.if t \{\
.    ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
.    ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
.    ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
.    ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
.    ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
.    ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
.\}
.    \" troff and (daisy-wheel) nroff accents
.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
.ds ae a\h'-(\w'a'u*4/10)'e
.ds Ae A\h'-(\w'A'u*4/10)'E
.    \" corrections for vroff
.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
.    \" for low resolution devices (crt and lpr)
.if \n(.H>23 .if \n(.V>19 \
\{\
.    ds : e
.    ds 8 ss
.    ds o a
.    ds d- d\h'-1'\(ga
.    ds D- D\h'-1'\(hy
.    ds th \o'bp'
.    ds Th \o'LP'
.    ds ae ae
.    ds Ae AE
.\}
.rm #[ #] #H #V #F C
.\" ========================================================================
.\"
.IX Title "PERLOBJ 1"
.TH PERLOBJ 1 "2002-11-24" "perl v5.8.0" "Perl Programmers Reference Guide"
.SH "NAME"
perlobj \- Perl objects
.SH "DESCRIPTION"
.IX Header "DESCRIPTION"
First you need to understand what references are in Perl.
See perlref 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 perltoot and perltooc.
.PP
If you're still with us, then
here are three very simple definitions that you should find reassuring.
.IP "1." 4
An object is simply a reference that happens to know which class it
belongs to.
.IP "2." 4
A class is simply a package that happens to provide methods to deal
with object references.
.IP "3." 4
A method is simply a subroutine that expects an object reference (or
a package name, for class methods) as the first argument.
.PP
We'll cover these points now in more depth.
.Sh "An Object is Simply a Reference"
.IX Subsection "An Object is Simply a Reference"
Unlike say \*(C+, Perl doesn't provide any special syntax for
constructors.  A constructor is merely a subroutine that returns a
reference to something \*(L"blessed\*(R" into a class, generally the
class that the subroutine is defined in.  Here is a typical
constructor:
.PP
.Vb 2
\&    package Critter;
\&    sub new { bless {} }
.Ve
.PP
That word \f(CW\*(C`new\*(C'\fR isn't special.  You could have written
a construct this way, too:
.PP
.Vb 2
\&    package Critter;
\&    sub spawn { bless {} }
.Ve
.PP
This might even be preferable, because the \*(C+ programmers won't
be tricked into thinking that \f(CW\*(C`new\*(C'\fR 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.
.PP
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 \f(CW\*(C`{}\*(C'\fR allocates an anonymous hash containing no
key/value pairs, and returns it  The \fIbless()\fR 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:
.PP
.Vb 5
\&    sub new {
\&        my $self = {};
\&        bless $self;
\&        return $self;
\&    }
.Ve
.PP
You often see such a thing in more complicated constructors
that wish to call methods in the class as part of the construction:
.PP
.Vb 6
\&    sub new {
\&        my $self = {};
\&        bless $self;
\&        $self->initialize();
\&        return $self;
\&    }
.Ve
.PP
If you care about inheritance (and you should; see
\&\*(L"Modules: Creation, Use, and Abuse\*(R" in perlmodlib),
then you want to use the two-arg form of bless
so that your constructors may be inherited:
.PP
.Vb 7
\&    sub new {
\&        my $class = shift;
\&        my $self = {};
\&        bless $self, $class;
\&        $self->initialize();
\&        return $self;
\&    }
.Ve
.PP
Or if you expect people to call not just \f(CW\*(C`CLASS\->new()\*(C'\fR but also
\&\f(CW\*(C`$obj\->new()\*(C'\fR, then use something like this.  The \fIinitialize()\fR
method used will be of whatever \f(CW$class\fR we blessed the
object into:
.PP
.Vb 8
\&    sub new {
\&        my $this = shift;
\&        my $class = ref($this) || $this;
\&        my $self = {};
\&        bless $self, $class;
\&        $self->initialize();
\&        return $self;
\&    }
.Ve
.PP
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.
.PP
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.
.PP
A clarification:  Perl objects are blessed.  References are not.  Objects
know which package they belong to.  References do not.  The \fIbless()\fR
function uses the reference to find the object.  Consider
the following example:
.PP
.Vb 4
\&    $a = {};
\&    $b = $a;
\&    bless $a, BLAH;
\&    print "\e$b is a ", ref($b), "\en";
.Ve
.PP
This reports \f(CW$b\fR as being a \s-1BLAH\s0, so obviously \fIbless()\fR
operated on the object and not on the reference.
.Sh "A Class is Simply a Package"
.IX Subsection "A Class is Simply a Package"
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.
.PP
There is a special array within each package called \f(CW@ISA\fR, 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
\&\f(CW@ISA\fR 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 \f(CW@ISA\fR.  The classes accessible
through \f(CW@ISA\fR are known as base classes of the current class.
.PP
All classes implicitly inherit from class \f(CW\*(C`UNIVERSAL\*(C'\fR as their
last base class.  Several commonly used methods are automatically
supplied in the \s-1UNIVERSAL\s0 class; see \*(L"Default \s-1UNIVERSAL\s0 methods\*(R" for
more details.
.PP
If a missing method is found in a base class, it is cached
in the current class for efficiency.  Changing \f(CW@ISA\fR or defining new
subroutines invalidates the cache and causes Perl to do the lookup again.
.PP
If neither the current class, its named base classes, nor the \s-1UNIVERSAL\s0
class contains the requested method, these three places are searched
all over again, this time looking for a method named \s-1\fIAUTOLOAD\s0()\fR.  If an
\&\s-1AUTOLOAD\s0 is found, this method is called on behalf of the missing method,
setting the package global \f(CW$AUTOLOAD\fR to be the fully qualified name of
the method that was intended to be called.
.PP
If none of that works, Perl finally gives up and complains.
.PP
If you want to stop the \s-1AUTOLOAD\s0 inheritance say simply
.PP
.Vb 1
\&        sub AUTOLOAD;
.Ve
.PP
and the call will die using the name of the sub being called.
.PP
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.
.PP
.Vb 4
\&    sub bump {
\&        my $self = shift;
\&        $self->{ __PACKAGE__ . ".count"}++;
\&    }
.Ve
.Sh "A Method is Simply a Subroutine"
.IX Subsection "A Method is Simply a Subroutine"
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.  
.PP
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 perltoot and perltooc 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:
.PP
.Vb 4
\&    sub find {
\&        my ($class, $name) = @_;
\&        $objtable{$name};
\&    }
.Ve
.PP
An instance method expects an object reference as its first argument.
Typically it shifts the first argument into a \*(L"self\*(R" or \*(L"this\*(R" variable,
and then uses that as an ordinary reference.
.PP
.Vb 7
\&    sub display {
\&        my $self = shift;
\&        my @keys = @_ ? @_ : sort keys %$self;
\&        foreach $key (@keys) {
\&            print "\et$key => $self->{$key}\en";
\&        }
\&    }
.Ve
.Sh "Method Invocation"
.IX Subsection "Method Invocation"
For various historical and other reasons, Perl offers two equivalent
ways to write a method call.  The simpler and more common way is to use
the arrow notation:
.PP
.Vb 2
\&    my $fred = Critter->find("Fred");
\&    $fred->display("Height", "Weight");
.Ve
.PP
You should already be familiar with the use of the \f(CW\*(C`\->\*(C'\fR operator with
references.  In fact, since \f(CW$fred\fR above is a reference to an object,
you could think of the method call as just another form of
dereferencing.
.PP
Whatever is on the left side of the arrow, whether a reference or a
class name, is passed to the method subroutine as its first argument.
So the above code is mostly equivalent to:
.PP
.Vb 2
\&    my $fred = Critter::find("Critter", "Fred");
\&    Critter::display($fred, "Height", "Weight");
.Ve
.PP
How does Perl know which package the subroutine is in?  By looking at
the left side of the arrow, which must be either a package name or a
reference to an object, i.e. something that has been blessed to a
package.  Either way, that's the package where Perl starts looking.  If
that package has no subroutine with that name, Perl starts looking for
it in any base classes of that package, and so on.
.PP
If you need to, you \fIcan\fR force Perl to start looking in some other package:
.PP
.Vb 2
\&    my $barney = MyCritter->Critter::find("Barney");
\&    $barney->Critter::display("Height", "Weight");
.Ve
.PP
Here \f(CW\*(C`MyCritter\*(C'\fR is presumably a subclass of \f(CW\*(C`Critter\*(C'\fR that defines
its own versions of \fIfind()\fR and \fIdisplay()\fR.  We haven't specified what
those methods do, but that doesn't matter above since we've forced Perl
to start looking for the subroutines in \f(CW\*(C`Critter\*(C'\fR.
.PP
As a special case of the above, you may use the \f(CW\*(C`SUPER\*(C'\fR pseudo-class to
tell Perl to start looking for the method in the packages named in the
current class's \f(CW@ISA\fR list.  
.PP
.Vb 2
\&    package MyCritter;
\&    use base 'Critter';    # sets @MyCritter::ISA = ('Critter');
.Ve
.PP
.Vb 4
\&    sub display { 
\&        my ($self, @args) = @_;
\&        $self->SUPER::display("Name", @args);
\&    }
.Ve
.PP
Instead of a class name or an object reference, you can also use any
expression that returns either of those on the left side of the arrow.
So the following statement is valid:
.PP
.Vb 1
\&    Critter->find("Fred")->display("Height", "Weight");
.Ve
.PP
and so is the following:
.PP
.Vb 1
\&    my $fred = (reverse "rettirC")->find(reverse "derF");
.Ve
.Sh "Indirect Object Syntax"
.IX Subsection "Indirect Object Syntax"
The other way to invoke a method is by using the so-called \*(L"indirect
object\*(R" notation.  This syntax was available in Perl 4 long before
objects were introduced, and is still used with filehandles like this:
.PP
.Vb 1
\&   print STDERR "help!!!\en";
.Ve
.PP
The same syntax can be used to call either object or class methods.
.PP
.Vb 2
\&   my $fred = find Critter "Fred";
\&   display $fred "Height", "Weight";
.Ve
.PP
Notice that there is no comma between the object or class name and the
parameters.  This is how Perl can tell you want an indirect method call
instead of an ordinary subroutine call.
.PP
But what if there are no arguments?  In that case, Perl must guess what
you want.  Even worse, it must make that guess \fIat compile time\fR.
Usually Perl gets it right, but when it doesn't you get a function
call compiled as a method, or vice versa.  This can introduce subtle bugs
that are hard to detect.
.PP
For example, a call to a method \f(CW\*(C`new\*(C'\fR in indirect notation \*(-- as \*(C+
programmers are wont to make \*(-- can be miscompiled into a subroutine
call if there's already a \f(CW\*(C`new\*(C'\fR function in scope.  You'd end up
calling the current package's \f(CW\*(C`new\*(C'\fR as a subroutine, rather than the
desired class's method.  The compiler tries to cheat by remembering
bareword \f(CW\*(C`require\*(C'\fRs, but the grief when it messes up just isn't worth the
years of debugging it will take you to track down such subtle bugs.
.PP
There is another problem with this syntax: the 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 \f(CW\*(C`print\*(C'\fR and \f(CW\*(C`printf\*(C'\fR.)
This can lead to horribly confusing precedence problems, as in these
next two lines:
.PP
.Vb 2
\&    move $obj->{FIELD};                 # probably wrong!
\&    move $ary[$i];                      # probably wrong!
.Ve
.PP
Those actually parse as the very surprising:
.PP
.Vb 2
\&    $obj->move->{FIELD};                # Well, lookee here
\&    $ary->move([$i]);                   # Didn't expect this one, eh?
.Ve
.PP
Rather than what you might have expected:
.PP
.Vb 2
\&    $obj->{FIELD}->move();              # You should be so lucky.
\&    $ary[$i]->move;                     # Yeah, sure.
.Ve
.PP
To get the correct behavior with indirect object syntax, you would have
to use a block around the indirect object:
.PP
.Vb 2
\&    move {$obj->{FIELD}};
\&    move {$ary[$i]};
.Ve
.PP
Even then, you still have the same potential problem if there happens to
be a function named \f(CW\*(C`move\*(C'\fR in the current package.  \fBThe \f(CB\*(C`\->\*(C'\fB
notation suffers from neither of these disturbing ambiguities, so we
recommend you use it exclusively.\fR  However, you may still end up having
to read code using the indirect object notation, so it's important to be
familiar with it.
.Sh "Default \s-1UNIVERSAL\s0 methods"
.IX Subsection "Default UNIVERSAL methods"
The \f(CW\*(C`UNIVERSAL\*(C'\fR package automatically contains the following methods that
are inherited by all other classes:
.IP "isa(\s-1CLASS\s0)" 4
.IX Item "isa(CLASS)"
\&\f(CW\*(C`isa\*(C'\fR returns \fItrue\fR if its object is blessed into a subclass of \f(CW\*(C`CLASS\*(C'\fR
.Sp
You can also call \f(CW\*(C`UNIVERSAL::isa\*(C'\fR as a subroutine with two arguments.
The first does not need to be an object or even a reference.  This
allows you to check what a reference points to, or whether
something is a reference of a given type. Example
.Sp
.Vb 3
\&    if(UNIVERSAL::isa($ref, 'ARRAY')) {
\&        #...
\&    }
.Ve
.Sp
To determine if a reference is a blessed object, you can write
.Sp
.Vb 1
\&    print "It's an object\en" if UNIVERSAL::isa($val, 'UNIVERSAL');
.Ve
.IP "can(\s-1METHOD\s0)" 4
.IX Item "can(METHOD)"
\&\f(CW\*(C`can\*(C'\fR checks to see if its object has a method called \f(CW\*(C`METHOD\*(C'\fR,
if it does then a reference to the sub is returned, if it does not then
\&\fIundef\fR is returned.
.Sp
\&\f(CW\*(C`UNIVERSAL::can\*(C'\fR can also be called as a subroutine with two arguments.
It'll always return \fIundef\fR if its first argument isn't an object or a
class name.    So here's another way to check if a reference is a
blessed object
.Sp
.Vb 1
\&    print "It's still an object\en" if UNIVERSAL::can($val, 'can');
.Ve
.Sp
You can also use the \f(CW\*(C`blessed\*(C'\fR function of Scalar::Util:
.Sp
.Vb 1
\&    use Scalar::Util 'blessed';
.Ve
.Sp
.Vb 1
\&    my $blessing = blessed $suspected_object;
.Ve
.Sp
\&\f(CW\*(C`blessed\*(C'\fR returns the name of the package the argument has been
blessed into, or \f(CW\*(C`undef\*(C'\fR.
.IP "\s-1VERSION\s0( [\s-1NEED\s0] )" 4
.IX Item "VERSION( [NEED] )"
\&\f(CW\*(C`VERSION\*(C'\fR returns the version number of the class (package).  If the
\&\s-1NEED\s0 argument is given then it will check that the current version (as
defined by the \f(CW$VERSION\fR variable in the given package) not less than
\&\s-1NEED\s0; it will die if this is not the case.  This method is normally
called as a class method.  This method is called automatically by the
\&\f(CW\*(C`VERSION\*(C'\fR form of \f(CW\*(C`use\*(C'\fR.
.Sp
.Vb 3
\&    use A 1.2 qw(some imported subs);
\&    # implies:
\&    A->VERSION(1.2);
.Ve
.PP
\&\fB\s-1NOTE:\s0\fR \f(CW\*(C`can\*(C'\fR directly uses Perl's internal code for method lookup, and
\&\f(CW\*(C`isa\*(C'\fR uses a very similar method and cache-ing strategy. This may cause
strange effects if the Perl code dynamically changes \f(CW@ISA\fR in any package.
.PP
You may add other methods to the \s-1UNIVERSAL\s0 class via Perl or \s-1XS\s0 code.
You do not need to \f(CW\*(C`use UNIVERSAL\*(C'\fR to make these methods
available to your program (and you should not do so).
.Sh "Destructors"
.IX Subsection "Destructors"
When the last reference to an object goes away, the object is
automatically destroyed.  (This may even be after you exit, if you've
stored references in global variables.)  If you want to capture control
just before the object is freed, you may define a \s-1DESTROY\s0 method in
your class.  It will automatically be called at the appropriate moment,
and you can do any extra cleanup you need to do.  Perl passes a reference
to the object under destruction as the first (and only) argument.  Beware
that the reference is a read-only value, and cannot be modified by
manipulating \f(CW$_[0]\fR within the destructor.  The object itself (i.e.
the thingy the reference points to, namely \f(CW\*(C`${$_[0]}\*(C'\fR, \f(CW\*(C`@{$_[0]}\*(C'\fR, 
\&\f(CW\*(C`%{$_[0]}\*(C'\fR etc.) is not similarly constrained.
.PP
If you arrange to re-bless the reference before the destructor returns,
perl will again call the \s-1DESTROY\s0 method for the re-blessed object after
the current one returns.  This can be used for clean delegation of
object destruction, or for ensuring that destructors in the base classes
of your choosing get called.  Explicitly calling \s-1DESTROY\s0 is also possible,
but is usually never needed.
.PP
Do not confuse the previous discussion with how objects \fI\s-1CONTAINED\s0\fR in the current
one are destroyed.  Such objects will be freed and destroyed automatically
when the current object is freed, provided no other references to them exist
elsewhere.
.Sh "Summary"
.IX Subsection "Summary"
That's about all there is to it.  Now you need just to go off and buy a
book about object-oriented design methodology, and bang your forehead
with it for the next six months or so.
.Sh "Two-Phased Garbage Collection"
.IX Subsection "Two-Phased Garbage Collection"
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 \f(CW\*(C`\-O\*(C'\fR flag, performance
will suffer.  If you \fIhave\fR built Perl with \f(CW\*(C`cc \-O\*(C'\fR, then this
probably won't matter.
.PP
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:
.PP
.Vb 4
\&    {
\&        my $a;
\&        $a = \e$a;
\&    }
.Ve
.PP
Even thought \f(CW$a\fR \fIshould\fR 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:
.PP
.Vb 8
\&    sub new_node {
\&        my $self = shift;
\&        my $class = ref($self) || $self;
\&        my $node = {};
\&        $node->{LEFT} = $node->{RIGHT} = $node;
\&        $node->{DATA} = [ @_ ];
\&        return bless $node => $class;
\&    }
.Ve
.PP
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.)
.PP
Almost.
.PP
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:
.PP
.Vb 2
\&    #!/usr/bin/perl
\&    package Subtle;
.Ve
.PP
.Vb 6
\&    sub new {
\&        my $test;
\&        $test = \e$test;
\&        warn "CREATING " . \e$test;
\&        return bless \e$test;
\&    }
.Ve
.PP
.Vb 4
\&    sub DESTROY {
\&        my $self = shift;
\&        warn "DESTROYING $self";
\&    }
.Ve
.PP
.Vb 1
\&    package main;
.Ve
.PP
.Vb 7
\&    warn "starting program";
\&    {
\&        my $a = Subtle->new;
\&        my $b = Subtle->new;
\&        $$a = 0;  # break selfref
\&        warn "leaving block";
\&    }
.Ve
.PP
.Vb 3
\&    warn "just exited block";
\&    warn "time to die...";
\&    exit;
.Ve
.PP
When run as \fI/tmp/test\fR, the following output is produced:
.PP
.Vb 8
\&    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.
.Ve
.PP
Notice that \*(L"global destruction\*(R" bit there?  That's the thread
garbage collector reaching the unreachable.
.PP
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 \s-1PERL_DESTRUCT_LEVEL\s0 environment variable, presuming
\&\f(CW\*(C`\-DDEBUGGING\*(C'\fR was enabled during perl build time.
See \*(L"\s-1PERL_DESTRUCT_LEVEL\s0\*(R" in perlhack for more information.
.PP
A more complete garbage collection strategy will be implemented
at a future date.
.PP
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 \s-1DESTROY\s0 method for the containing object's class that manually
breaks the circularities in the self-referential structure.
.SH "SEE ALSO"
.IX Header "SEE ALSO"
A kinder, gentler tutorial on object-oriented programming in Perl can
be found in perltoot, perlboot and perltooc.  You should
also check out perlbot for other object tricks, traps, and tips, as
well as perlmodlib for some style guides on constructing both
modules and classes.

Bell Labs OSI certified Powered by Plan 9

(Return to Plan 9 Home Page)

Copyright © 2021 Plan 9 Foundation. All Rights Reserved.
Comments to [email protected].