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

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 "PERLBOOT 1"
.TH PERLBOOT 1 "2002-11-24" "perl v5.8.0" "Perl Programmers Reference Guide"
.SH "NAME"
perlboot \- Beginner's Object\-Oriented Tutorial
.SH "DESCRIPTION"
.IX Header "DESCRIPTION"
If you're not familiar with objects from other languages, some of the
other Perl object documentation may be a little daunting, such as
perlobj, a basic reference in using objects, and perltoot, which
introduces readers to the peculiarities of Perl's object system in a
tutorial way.
.PP
So, let's take a different approach, presuming no prior object
experience. It helps if you know about subroutines (perlsub),
references (perlref et. seq.), and packages (perlmod), so become
familiar with those first if you haven't already.
.Sh "If we could talk to the animals..."
.IX Subsection "If we could talk to the animals..."
Let's let the animals talk for a moment:
.PP
.Vb 9
\&    sub Cow::speak {
\&      print "a Cow goes moooo!\en";
\&    }
\&    sub Horse::speak {
\&      print "a Horse goes neigh!\en";
\&    }
\&    sub Sheep::speak {
\&      print "a Sheep goes baaaah!\en"
\&    }
.Ve
.PP
.Vb 3
\&    Cow::speak;
\&    Horse::speak;
\&    Sheep::speak;
.Ve
.PP
This results in:
.PP
.Vb 3
\&    a Cow goes moooo!
\&    a Horse goes neigh!
\&    a Sheep goes baaaah!
.Ve
.PP
Nothing spectacular here.  Simple subroutines, albeit from separate
packages, and called using the full package name.  So let's create
an entire pasture:
.PP
.Vb 5
\&    # Cow::speak, Horse::speak, Sheep::speak as before
\&    @pasture = qw(Cow Cow Horse Sheep Sheep);
\&    foreach $animal (@pasture) {
\&      &{$animal."::speak"};
\&    }
.Ve
.PP
This results in:
.PP
.Vb 5
\&    a Cow goes moooo!
\&    a Cow goes moooo!
\&    a Horse goes neigh!
\&    a Sheep goes baaaah!
\&    a Sheep goes baaaah!
.Ve
.PP
Wow.  That symbolic coderef de-referencing there is pretty nasty.
We're counting on \f(CW\*(C`no strict subs\*(C'\fR mode, certainly not recommended
for larger programs.  And why was that necessary?  Because the name of
the package seems to be inseparable from the name of the subroutine we
want to invoke within that package.
.PP
Or is it?
.Sh "Introducing the method invocation arrow"
.IX Subsection "Introducing the method invocation arrow"
For now, let's say that \f(CW\*(C`Class\->method\*(C'\fR invokes subroutine
\&\f(CW\*(C`method\*(C'\fR in package \f(CW\*(C`Class\*(C'\fR.  (Here, \*(L"Class\*(R" is used in its
\&\*(L"category\*(R" meaning, not its \*(L"scholastic\*(R" meaning.) That's not
completely accurate, but we'll do this one step at a time.  Now let's
use it like so:
.PP
.Vb 4
\&    # Cow::speak, Horse::speak, Sheep::speak as before
\&    Cow->speak;
\&    Horse->speak;
\&    Sheep->speak;
.Ve
.PP
And once again, this results in:
.PP
.Vb 3
\&    a Cow goes moooo!
\&    a Horse goes neigh!
\&    a Sheep goes baaaah!
.Ve
.PP
That's not fun yet.  Same number of characters, all constant, no
variables.  But yet, the parts are separable now.  Watch:
.PP
.Vb 2
\&    $a = "Cow";
\&    $a->speak; # invokes Cow->speak
.Ve
.PP
Ahh!  Now that the package name has been parted from the subroutine
name, we can use a variable package name.  And this time, we've got
something that works even when \f(CW\*(C`use strict refs\*(C'\fR is enabled.
.Sh "Invoking a barnyard"
.IX Subsection "Invoking a barnyard"
Let's take that new arrow invocation and put it back in the barnyard
example:
.PP
.Vb 9
\&    sub Cow::speak {
\&      print "a Cow goes moooo!\en";
\&    }
\&    sub Horse::speak {
\&      print "a Horse goes neigh!\en";
\&    }
\&    sub Sheep::speak {
\&      print "a Sheep goes baaaah!\en"
\&    }
.Ve
.PP
.Vb 4
\&    @pasture = qw(Cow Cow Horse Sheep Sheep);
\&    foreach $animal (@pasture) {
\&      $animal->speak;
\&    }
.Ve
.PP
There!  Now we have the animals all talking, and safely at that,
without the use of symbolic coderefs.
.PP
But look at all that common code.  Each of the \f(CW\*(C`speak\*(C'\fR routines has a
similar structure: a \f(CW\*(C`print\*(C'\fR operator and a string that contains
common text, except for two of the words.  It'd be nice if we could
factor out the commonality, in case we decide later to change it all
to \f(CW\*(C`says\*(C'\fR instead of \f(CW\*(C`goes\*(C'\fR.
.PP
And we actually have a way of doing that without much fuss, but we
have to hear a bit more about what the method invocation arrow is
actually doing for us.
.Sh "The extra parameter of method invocation"
.IX Subsection "The extra parameter of method invocation"
The invocation of:
.PP
.Vb 1
\&    Class->method(@args)
.Ve
.PP
attempts to invoke subroutine \f(CW\*(C`Class::method\*(C'\fR as:
.PP
.Vb 1
\&    Class::method("Class", @args);
.Ve
.PP
(If the subroutine can't be found, \*(L"inheritance\*(R" kicks in, but we'll
get to that later.)  This means that we get the class name as the
first parameter (the only parameter, if no arguments are given).  So
we can rewrite the \f(CW\*(C`Sheep\*(C'\fR speaking subroutine as:
.PP
.Vb 4
\&    sub Sheep::speak {
\&      my $class = shift;
\&      print "a $class goes baaaah!\en";
\&    }
.Ve
.PP
And the other two animals come out similarly:
.PP
.Vb 8
\&    sub Cow::speak {
\&      my $class = shift;
\&      print "a $class goes moooo!\en";
\&    }
\&    sub Horse::speak {
\&      my $class = shift;
\&      print "a $class goes neigh!\en";
\&    }
.Ve
.PP
In each case, \f(CW$class\fR will get the value appropriate for that
subroutine.  But once again, we have a lot of similar structure.  Can
we factor that out even further?  Yes, by calling another method in
the same class.
.Sh "Calling a second method to simplify things"
.IX Subsection "Calling a second method to simplify things"
Let's call out from \f(CW\*(C`speak\*(C'\fR to a helper method called \f(CW\*(C`sound\*(C'\fR.
This method provides the constant text for the sound itself.
.PP
.Vb 7
\&    { package Cow;
\&      sub sound { "moooo" }
\&      sub speak {
\&        my $class = shift;
\&        print "a $class goes ", $class->sound, "!\en"
\&      }
\&    }
.Ve
.PP
Now, when we call \f(CW\*(C`Cow\->speak\*(C'\fR, we get a \f(CW$class\fR of \f(CW\*(C`Cow\*(C'\fR in
\&\f(CW\*(C`speak\*(C'\fR.  This in turn selects the \f(CW\*(C`Cow\->sound\*(C'\fR method, which
returns \f(CW\*(C`moooo\*(C'\fR.  But how different would this be for the \f(CW\*(C`Horse\*(C'\fR?
.PP
.Vb 7
\&    { package Horse;
\&      sub sound { "neigh" }
\&      sub speak {
\&        my $class = shift;
\&        print "a $class goes ", $class->sound, "!\en"
\&      }
\&    }
.Ve
.PP
Only the name of the package and the specific sound change.  So can we
somehow share the definition for \f(CW\*(C`speak\*(C'\fR between the Cow and the
Horse?  Yes, with inheritance!
.Sh "Inheriting the windpipes"
.IX Subsection "Inheriting the windpipes"
We'll define a common subroutine package called \f(CW\*(C`Animal\*(C'\fR, with the
definition for \f(CW\*(C`speak\*(C'\fR:
.PP
.Vb 6
\&    { package Animal;
\&      sub speak {
\&        my $class = shift;
\&        print "a $class goes ", $class->sound, "!\en"
\&      }
\&    }
.Ve
.PP
Then, for each animal, we say it \*(L"inherits\*(R" from \f(CW\*(C`Animal\*(C'\fR, along
with the animal-specific sound:
.PP
.Vb 4
\&    { package Cow;
\&      @ISA = qw(Animal);
\&      sub sound { "moooo" }
\&    }
.Ve
.PP
Note the added \f(CW@ISA\fR array.  We'll get to that in a minute.
.PP
But what happens when we invoke \f(CW\*(C`Cow\->speak\*(C'\fR now?
.PP
First, Perl constructs the argument list.  In this case, it's just
\&\f(CW\*(C`Cow\*(C'\fR.  Then Perl looks for \f(CW\*(C`Cow::speak\*(C'\fR.  But that's not there, so
Perl checks for the inheritance array \f(CW@Cow::ISA\fR.  It's there,
and contains the single name \f(CW\*(C`Animal\*(C'\fR.
.PP
Perl next checks for \f(CW\*(C`speak\*(C'\fR inside \f(CW\*(C`Animal\*(C'\fR instead, as in
\&\f(CW\*(C`Animal::speak\*(C'\fR.  And that's found, so Perl invokes that subroutine
with the already frozen argument list.
.PP
Inside the \f(CW\*(C`Animal::speak\*(C'\fR subroutine, \f(CW$class\fR becomes \f(CW\*(C`Cow\*(C'\fR (the
first argument).  So when we get to the step of invoking
\&\f(CW\*(C`$class\->sound\*(C'\fR, it'll be looking for \f(CW\*(C`Cow\->sound\*(C'\fR, which
gets it on the first try without looking at \f(CW@ISA\fR.  Success!
.ie n .Sh "A few notes about @ISA"
.el .Sh "A few notes about \f(CW@ISA\fP"
.IX Subsection "A few notes about @ISA"
This magical \f(CW@ISA\fR variable (pronounced \*(L"is a\*(R" not \*(L"ice\-uh\*(R"), has
declared that \f(CW\*(C`Cow\*(C'\fR \*(L"is a\*(R" \f(CW\*(C`Animal\*(C'\fR.  Note that it's an array,
not a simple single value, because on rare occasions, it makes sense
to have more than one parent class searched for the missing methods.
.PP
If \f(CW\*(C`Animal\*(C'\fR also had an \f(CW@ISA\fR, then we'd check there too.  The
search is recursive, depth\-first, left-to-right in each \f(CW@ISA\fR.
Typically, each \f(CW@ISA\fR has only one element (multiple elements means
multiple inheritance and multiple headaches), so we get a nice tree of
inheritance.
.PP
When we turn on \f(CW\*(C`use strict\*(C'\fR, we'll get complaints on \f(CW@ISA\fR, since
it's not a variable containing an explicit package name, nor is it a
lexical (\*(L"my\*(R") variable.  We can't make it a lexical variable though
(it has to belong to the package to be found by the inheritance mechanism),
so there's a couple of straightforward ways to handle that.
.PP
The easiest is to just spell the package name out:
.PP
.Vb 1
\&    @Cow::ISA = qw(Animal);
.Ve
.PP
Or allow it as an implicitly named package variable:
.PP
.Vb 3
\&    package Cow;
\&    use vars qw(@ISA);
\&    @ISA = qw(Animal);
.Ve
.PP
If you're bringing in the class from outside, via an object-oriented
module, you change:
.PP
.Vb 4
\&    package Cow;
\&    use Animal;
\&    use vars qw(@ISA);
\&    @ISA = qw(Animal);
.Ve
.PP
into just:
.PP
.Vb 2
\&    package Cow;
\&    use base qw(Animal);
.Ve
.PP
And that's pretty darn compact.
.Sh "Overriding the methods"
.IX Subsection "Overriding the methods"
Let's add a mouse, which can barely be heard:
.PP
.Vb 10
\&    # Animal package from before
\&    { package Mouse;
\&      @ISA = qw(Animal);
\&      sub sound { "squeak" }
\&      sub speak {
\&        my $class = shift;
\&        print "a $class goes ", $class->sound, "!\en";
\&        print "[but you can barely hear it!]\en";
\&      }
\&    }
.Ve
.PP
.Vb 1
\&    Mouse->speak;
.Ve
.PP
which results in:
.PP
.Vb 2
\&    a Mouse goes squeak!
\&    [but you can barely hear it!]
.Ve
.PP
Here, \f(CW\*(C`Mouse\*(C'\fR has its own speaking routine, so \f(CW\*(C`Mouse\->speak\*(C'\fR
doesn't immediately invoke \f(CW\*(C`Animal\->speak\*(C'\fR.  This is known as
\&\*(L"overriding\*(R".  In fact, we didn't even need to say that a \f(CW\*(C`Mouse\*(C'\fR was
an \f(CW\*(C`Animal\*(C'\fR at all, since all of the methods needed for \f(CW\*(C`speak\*(C'\fR are
completely defined with \f(CW\*(C`Mouse\*(C'\fR.
.PP
But we've now duplicated some of the code from \f(CW\*(C`Animal\->speak\*(C'\fR,
and this can once again be a maintenance headache.  So, can we avoid
that?  Can we say somehow that a \f(CW\*(C`Mouse\*(C'\fR does everything any other
\&\f(CW\*(C`Animal\*(C'\fR does, but add in the extra comment?  Sure!
.PP
First, we can invoke the \f(CW\*(C`Animal::speak\*(C'\fR method directly:
.PP
.Vb 10
\&    # Animal package from before
\&    { package Mouse;
\&      @ISA = qw(Animal);
\&      sub sound { "squeak" }
\&      sub speak {
\&        my $class = shift;
\&        Animal::speak($class);
\&        print "[but you can barely hear it!]\en";
\&      }
\&    }
.Ve
.PP
Note that we have to include the \f(CW$class\fR parameter (almost surely
the value of \f(CW"Mouse"\fR) as the first parameter to \f(CW\*(C`Animal::speak\*(C'\fR,
since we've stopped using the method arrow.  Why did we stop?  Well,
if we invoke \f(CW\*(C`Animal\->speak\*(C'\fR there, the first parameter to the
method will be \f(CW"Animal"\fR not \f(CW"Mouse"\fR, and when time comes for it
to call for the \f(CW\*(C`sound\*(C'\fR, it won't have the right class to come back
to this package.
.PP
Invoking \f(CW\*(C`Animal::speak\*(C'\fR directly is a mess, however.  What if
\&\f(CW\*(C`Animal::speak\*(C'\fR didn't exist before, and was being inherited from a
class mentioned in \f(CW@Animal::ISA\fR?  Because we are no longer using
the method arrow, we get one and only one chance to hit the right
subroutine.
.PP
Also note that the \f(CW\*(C`Animal\*(C'\fR classname is now hardwired into the
subroutine selection.  This is a mess if someone maintains the code,
changing \f(CW@ISA\fR for <Mouse> and didn't notice \f(CW\*(C`Animal\*(C'\fR there in
\&\f(CW\*(C`speak\*(C'\fR.  So, this is probably not the right way to go.
.Sh "Starting the search from a different place"
.IX Subsection "Starting the search from a different place"
A better solution is to tell Perl to search from a higher place
in the inheritance chain:
.PP
.Vb 9
\&    # same Animal as before
\&    { package Mouse;
\&      # same @ISA, &sound as before
\&      sub speak {
\&        my $class = shift;
\&        $class->Animal::speak;
\&        print "[but you can barely hear it!]\en";
\&      }
\&    }
.Ve
.PP
Ahh.  This works.  Using this syntax, we start with \f(CW\*(C`Animal\*(C'\fR to find
\&\f(CW\*(C`speak\*(C'\fR, and use all of \f(CW\*(C`Animal\*(C'\fR's inheritance chain if not found
immediately.  And yet the first parameter will be \f(CW$class\fR, so the
found \f(CW\*(C`speak\*(C'\fR method will get \f(CW\*(C`Mouse\*(C'\fR as its first entry, and
eventually work its way back to \f(CW\*(C`Mouse::sound\*(C'\fR for the details.
.PP
But this isn't the best solution.  We still have to keep the \f(CW@ISA\fR
and the initial search package coordinated.  Worse, if \f(CW\*(C`Mouse\*(C'\fR had
multiple entries in \f(CW@ISA\fR, we wouldn't necessarily know which one
had actually defined \f(CW\*(C`speak\*(C'\fR.  So, is there an even better way?
.Sh "The \s-1SUPER\s0 way of doing things"
.IX Subsection "The SUPER way of doing things"
By changing the \f(CW\*(C`Animal\*(C'\fR class to the \f(CW\*(C`SUPER\*(C'\fR class in that
invocation, we get a search of all of our super classes (classes
listed in \f(CW@ISA\fR) automatically:
.PP
.Vb 9
\&    # same Animal as before
\&    { package Mouse;
\&      # same @ISA, &sound as before
\&      sub speak {
\&        my $class = shift;
\&        $class->SUPER::speak;
\&        print "[but you can barely hear it!]\en";
\&      }
\&    }
.Ve
.PP
So, \f(CW\*(C`SUPER::speak\*(C'\fR means look in the current package's \f(CW@ISA\fR for
\&\f(CW\*(C`speak\*(C'\fR, invoking the first one found.
.Sh "Where we're at so far..."
.IX Subsection "Where we're at so far..."
So far, we've seen the method arrow syntax:
.PP
.Vb 1
\&  Class->method(@args);
.Ve
.PP
or the equivalent:
.PP
.Vb 2
\&  $a = "Class";
\&  $a->method(@args);
.Ve
.PP
which constructs an argument list of:
.PP
.Vb 1
\&  ("Class", @args)
.Ve
.PP
and attempts to invoke
.PP
.Vb 1
\&  Class::method("Class", @Args);
.Ve
.PP
However, if \f(CW\*(C`Class::method\*(C'\fR is not found, then \f(CW@Class::ISA\fR is examined
(recursively) to locate a package that does indeed contain \f(CW\*(C`method\*(C'\fR,
and that subroutine is invoked instead.
.PP
Using this simple syntax, we have class methods, (multiple)
inheritance, overriding, and extending.  Using just what we've seen so
far, we've been able to factor out common code, and provide a nice way
to reuse implementations with variations.  This is at the core of what
objects provide, but objects also provide instance data, which we
haven't even begun to cover.
.Sh "A horse is a horse, of course of course \*(-- or is it?"
.IX Subsection "A horse is a horse, of course of course  or is it?"
Let's start with the code for the \f(CW\*(C`Animal\*(C'\fR class
and the \f(CW\*(C`Horse\*(C'\fR class:
.PP
.Vb 10
\&  { package Animal;
\&    sub speak {
\&      my $class = shift;
\&      print "a $class goes ", $class->sound, "!\en"
\&    }
\&  }
\&  { package Horse;
\&    @ISA = qw(Animal);
\&    sub sound { "neigh" }
\&  }
.Ve
.PP
This lets us invoke \f(CW\*(C`Horse\->speak\*(C'\fR to ripple upward to
\&\f(CW\*(C`Animal::speak\*(C'\fR, calling back to \f(CW\*(C`Horse::sound\*(C'\fR to get the specific
sound, and the output of:
.PP
.Vb 1
\&  a Horse goes neigh!
.Ve
.PP
But all of our Horse objects would have to be absolutely identical.
If I add a subroutine, all horses automatically share it.  That's
great for making horses the same, but how do we capture the
distinctions about an individual horse?  For example, suppose I want
to give my first horse a name.  There's got to be a way to keep its
name separate from the other horses.
.PP
We can do that by drawing a new distinction, called an \*(L"instance\*(R".
An \*(L"instance\*(R" is generally created by a class.  In Perl, any reference
can be an instance, so let's start with the simplest reference
that can hold a horse's name: a scalar reference.
.PP
.Vb 2
\&  my $name = "Mr. Ed";
\&  my $talking = \e$name;
.Ve
.PP
So now \f(CW$talking\fR is a reference to what will be the instance-specific
data (the name).  The final step in turning this into a real instance
is with a special operator called \f(CW\*(C`bless\*(C'\fR:
.PP
.Vb 1
\&  bless $talking, Horse;
.Ve
.PP
This operator stores information about the package named \f(CW\*(C`Horse\*(C'\fR into
the thing pointed at by the reference.  At this point, we say
\&\f(CW$talking\fR is an instance of \f(CW\*(C`Horse\*(C'\fR.  That is, it's a specific
horse.  The reference is otherwise unchanged, and can still be used
with traditional dereferencing operators.
.Sh "Invoking an instance method"
.IX Subsection "Invoking an instance method"
The method arrow can be used on instances, as well as names of
packages (classes).  So, let's get the sound that \f(CW$talking\fR makes:
.PP
.Vb 1
\&  my $noise = $talking->sound;
.Ve
.PP
To invoke \f(CW\*(C`sound\*(C'\fR, Perl first notes that \f(CW$talking\fR is a blessed
reference (and thus an instance).  It then constructs an argument
list, in this case from just \f(CW\*(C`($talking)\*(C'\fR.  (Later we'll see that
arguments will take their place following the instance variable,
just like with classes.)
.PP
Now for the fun part: Perl takes the class in which the instance was
blessed, in this case \f(CW\*(C`Horse\*(C'\fR, and uses that to locate the subroutine
to invoke the method.  In this case, \f(CW\*(C`Horse::sound\*(C'\fR is found directly
(without using inheritance), yielding the final subroutine invocation:
.PP
.Vb 1
\&  Horse::sound($talking)
.Ve
.PP
Note that the first parameter here is still the instance, not the name
of the class as before.  We'll get \f(CW\*(C`neigh\*(C'\fR as the return value, and
that'll end up as the \f(CW$noise\fR variable above.
.PP
If Horse::sound had not been found, we'd be wandering up the
\&\f(CW@Horse::ISA\fR list to try to find the method in one of the
superclasses, just as for a class method.  The only difference between
a class method and an instance method is whether the first parameter
is an instance (a blessed reference) or a class name (a string).
.Sh "Accessing the instance data"
.IX Subsection "Accessing the instance data"
Because we get the instance as the first parameter, we can now access
the instance-specific data.  In this case, let's add a way to get at
the name:
.PP
.Vb 8
\&  { package Horse;
\&    @ISA = qw(Animal);
\&    sub sound { "neigh" }
\&    sub name {
\&      my $self = shift;
\&      $$self;
\&    }
\&  }
.Ve
.PP
Now we call for the name:
.PP
.Vb 1
\&  print $talking->name, " says ", $talking->sound, "\en";
.Ve
.PP
Inside \f(CW\*(C`Horse::name\*(C'\fR, the \f(CW@_\fR array contains just \f(CW$talking\fR,
which the \f(CW\*(C`shift\*(C'\fR stores into \f(CW$self\fR.  (It's traditional to shift
the first parameter off into a variable named \f(CW$self\fR for instance
methods, so stay with that unless you have strong reasons otherwise.)
Then, \f(CW$self\fR gets de-referenced as a scalar ref, yielding \f(CW\*(C`Mr. Ed\*(C'\fR,
and we're done with that.  The result is:
.PP
.Vb 1
\&  Mr. Ed says neigh.
.Ve
.Sh "How to build a horse"
.IX Subsection "How to build a horse"
Of course, if we constructed all of our horses by hand, we'd most
likely make mistakes from time to time.  We're also violating one of
the properties of object-oriented programming, in that the \*(L"inside
guts\*(R" of a Horse are visible.  That's good if you're a veterinarian,
but not if you just like to own horses.  So, let's let the Horse class
build a new horse:
.PP
.Vb 13
\&  { package Horse;
\&    @ISA = qw(Animal);
\&    sub sound { "neigh" }
\&    sub name {
\&      my $self = shift;
\&      $$self;
\&    }
\&    sub named {
\&      my $class = shift;
\&      my $name = shift;
\&      bless \e$name, $class;
\&    }
\&  }
.Ve
.PP
Now with the new \f(CW\*(C`named\*(C'\fR method, we can build a horse:
.PP
.Vb 1
\&  my $talking = Horse->named("Mr. Ed");
.Ve
.PP
Notice we're back to a class method, so the two arguments to
\&\f(CW\*(C`Horse::named\*(C'\fR are \f(CW\*(C`Horse\*(C'\fR and \f(CW\*(C`Mr. Ed\*(C'\fR.  The \f(CW\*(C`bless\*(C'\fR operator
not only blesses \f(CW$name\fR, it also returns the reference to \f(CW$name\fR,
so that's fine as a return value.  And that's how to build a horse.
.PP
We've called the constructor \f(CW\*(C`named\*(C'\fR here, so that it quickly denotes
the constructor's argument as the name for this particular \f(CW\*(C`Horse\*(C'\fR.
You can use different constructors with different names for different
ways of \*(L"giving birth\*(R" to the object (like maybe recording its
pedigree or date of birth).  However, you'll find that most people
coming to Perl from more limited languages use a single constructor
named \f(CW\*(C`new\*(C'\fR, with various ways of interpreting the arguments to
\&\f(CW\*(C`new\*(C'\fR.  Either style is fine, as long as you document your particular
way of giving birth to an object.  (And you \fIwere\fR going to do that,
right?)
.Sh "Inheriting the constructor"
.IX Subsection "Inheriting the constructor"
But was there anything specific to \f(CW\*(C`Horse\*(C'\fR in that method?  No.  Therefore,
it's also the same recipe for building anything else that inherited from
\&\f(CW\*(C`Animal\*(C'\fR, so let's put it there:
.PP
.Vb 19
\&  { package Animal;
\&    sub speak {
\&      my $class = shift;
\&      print "a $class goes ", $class->sound, "!\en"
\&    }
\&    sub name {
\&      my $self = shift;
\&      $$self;
\&    }
\&    sub named {
\&      my $class = shift;
\&      my $name = shift;
\&      bless \e$name, $class;
\&    }
\&  }
\&  { package Horse;
\&    @ISA = qw(Animal);
\&    sub sound { "neigh" }
\&  }
.Ve
.PP
Ahh, but what happens if we invoke \f(CW\*(C`speak\*(C'\fR on an instance?
.PP
.Vb 2
\&  my $talking = Horse->named("Mr. Ed");
\&  $talking->speak;
.Ve
.PP
We get a debugging value:
.PP
.Vb 1
\&  a Horse=SCALAR(0xaca42ac) goes neigh!
.Ve
.PP
Why?  Because the \f(CW\*(C`Animal::speak\*(C'\fR routine is expecting a classname as
its first parameter, not an instance.  When the instance is passed in,
we'll end up using a blessed scalar reference as a string, and that
shows up as we saw it just now.
.Sh "Making a method work with either classes or instances"
.IX Subsection "Making a method work with either classes or instances"
All we need is for a method to detect if it is being called on a class
or called on an instance.  The most straightforward way is with the
\&\f(CW\*(C`ref\*(C'\fR operator.  This returns a string (the classname) when used on a
blessed reference, and \f(CW\*(C`undef\*(C'\fR when used on a string (like a
classname).  Let's modify the \f(CW\*(C`name\*(C'\fR method first to notice the change:
.PP
.Vb 6
\&  sub name {
\&    my $either = shift;
\&    ref $either
\&      ? $$either # it's an instance, return name
\&      : "an unnamed $either"; # it's a class, return generic
\&  }
.Ve
.PP
Here, the \f(CW\*(C`?:\*(C'\fR operator comes in handy to select either the
dereference or a derived string.  Now we can use this with either an
instance or a class.  Note that I've changed the first parameter
holder to \f(CW$either\fR to show that this is intended:
.PP
.Vb 3
\&  my $talking = Horse->named("Mr. Ed");
\&  print Horse->name, "\en"; # prints "an unnamed Horse\en"
\&  print $talking->name, "\en"; # prints "Mr Ed.\en"
.Ve
.PP
and now we'll fix \f(CW\*(C`speak\*(C'\fR to use this:
.PP
.Vb 4
\&  sub speak {
\&    my $either = shift;
\&    print $either->name, " goes ", $either->sound, "\en";
\&  }
.Ve
.PP
And since \f(CW\*(C`sound\*(C'\fR already worked with either a class or an instance,
we're done!
.Sh "Adding parameters to a method"
.IX Subsection "Adding parameters to a method"
Let's train our animals to eat:
.PP
.Vb 30
\&  { package Animal;
\&    sub named {
\&      my $class = shift;
\&      my $name = shift;
\&      bless \e$name, $class;
\&    }
\&    sub name {
\&      my $either = shift;
\&      ref $either
\&        ? $$either # it's an instance, return name
\&        : "an unnamed $either"; # it's a class, return generic
\&    }
\&    sub speak {
\&      my $either = shift;
\&      print $either->name, " goes ", $either->sound, "\en";
\&    }
\&    sub eat {
\&      my $either = shift;
\&      my $food = shift;
\&      print $either->name, " eats $food.\en";
\&    }
\&  }
\&  { package Horse;
\&    @ISA = qw(Animal);
\&    sub sound { "neigh" }
\&  }
\&  { package Sheep;
\&    @ISA = qw(Animal);
\&    sub sound { "baaaah" }
\&  }
.Ve
.PP
And now try it out:
.PP
.Vb 3
\&  my $talking = Horse->named("Mr. Ed");
\&  $talking->eat("hay");
\&  Sheep->eat("grass");
.Ve
.PP
which prints:
.PP
.Vb 2
\&  Mr. Ed eats hay.
\&  an unnamed Sheep eats grass.
.Ve
.PP
An instance method with parameters gets invoked with the instance,
and then the list of parameters.  So that first invocation is like:
.PP
.Vb 1
\&  Animal::eat($talking, "hay");
.Ve
.Sh "More interesting instances"
.IX Subsection "More interesting instances"
What if an instance needs more data?  Most interesting instances are
made of many items, each of which can in turn be a reference or even
another object.  The easiest way to store these is often in a hash.
The keys of the hash serve as the names of parts of the object (often
called \*(L"instance variables\*(R" or \*(L"member variables\*(R"), and the
corresponding values are, well, the values.
.PP
But how do we turn the horse into a hash?  Recall that an object was
any blessed reference.  We can just as easily make it a blessed hash
reference as a blessed scalar reference, as long as everything that
looks at the reference is changed accordingly.
.PP
Let's make a sheep that has a name and a color:
.PP
.Vb 1
\&  my $bad = bless { Name => "Evil", Color => "black" }, Sheep;
.Ve
.PP
so \f(CW\*(C`$bad\->{Name}\*(C'\fR has \f(CW\*(C`Evil\*(C'\fR, and \f(CW\*(C`$bad\->{Color}\*(C'\fR has
\&\f(CW\*(C`black\*(C'\fR.  But we want to make \f(CW\*(C`$bad\->name\*(C'\fR access the name, and
that's now messed up because it's expecting a scalar reference.  Not
to worry, because that's pretty easy to fix up:
.PP
.Vb 7
\&  ## in Animal
\&  sub name {
\&    my $either = shift;
\&    ref $either ?
\&      $either->{Name} :
\&      "an unnamed $either";
\&  }
.Ve
.PP
And of course \f(CW\*(C`named\*(C'\fR still builds a scalar sheep, so let's fix that
as well:
.PP
.Vb 7
\&  ## in Animal
\&  sub named {
\&    my $class = shift;
\&    my $name = shift;
\&    my $self = { Name => $name, Color => $class->default_color };
\&    bless $self, $class;
\&  }
.Ve
.PP
What's this \f(CW\*(C`default_color\*(C'\fR?  Well, if \f(CW\*(C`named\*(C'\fR has only the name,
we still need to set a color, so we'll have a class-specific initial color.
For a sheep, we might define it as white:
.PP
.Vb 2
\&  ## in Sheep
\&  sub default_color { "white" }
.Ve
.PP
And then to keep from having to define one for each additional class,
we'll define a \*(L"backstop\*(R" method that serves as the \*(L"default default\*(R",
directly in \f(CW\*(C`Animal\*(C'\fR:
.PP
.Vb 2
\&  ## in Animal
\&  sub default_color { "brown" }
.Ve
.PP
Now, because \f(CW\*(C`name\*(C'\fR and \f(CW\*(C`named\*(C'\fR were the only methods that
referenced the \*(L"structure\*(R" of the object, the rest of the methods can
remain the same, so \f(CW\*(C`speak\*(C'\fR still works as before.
.Sh "A horse of a different color"
.IX Subsection "A horse of a different color"
But having all our horses be brown would be boring.  So let's add a
method or two to get and set the color.
.PP
.Vb 7
\&  ## in Animal
\&  sub color {
\&    $_[0]->{Color}
\&  }
\&  sub set_color {
\&    $_[0]->{Color} = $_[1];
\&  }
.Ve
.PP
Note the alternate way of accessing the arguments: \f(CW$_[0]\fR is used
in\-place, rather than with a \f(CW\*(C`shift\*(C'\fR.  (This saves us a bit of time
for something that may be invoked frequently.)  And now we can fix
that color for Mr. Ed:
.PP
.Vb 3
\&  my $talking = Horse->named("Mr. Ed");
\&  $talking->set_color("black-and-white");
\&  print $talking->name, " is colored ", $talking->color, "\en";
.Ve
.PP
which results in:
.PP
.Vb 1
\&  Mr. Ed is colored black-and-white
.Ve
.Sh "Summary"
.IX Subsection "Summary"
So, now we have class methods, constructors, instance methods,
instance data, and even accessors.  But that's still just the
beginning of what Perl has to offer.  We haven't even begun to talk
about accessors that double as getters and setters, destructors,
indirect object notation, subclasses that add instance data, per-class
data, overloading, \*(L"isa\*(R" and \*(L"can\*(R" tests, \f(CW\*(C`UNIVERSAL\*(C'\fR class, and so
on.  That's for the rest of the Perl documentation to cover.
Hopefully, this gets you started, though.
.SH "SEE ALSO"
.IX Header "SEE ALSO"
For more information, see perlobj (for all the gritty details about
Perl objects, now that you've seen the basics), perltoot (the
tutorial for those who already know objects), perltooc (dealing
with class data), perlbot (for some more tricks), and books such as
Damian Conway's excellent \fIObject Oriented Perl\fR.
.PP
Some modules which might prove interesting are Class::Accessor,
Class::Class, Class::Contract, Class::Data::Inheritable,
Class::MethodMaker and Tie::SecureHash
.SH "COPYRIGHT"
.IX Header "COPYRIGHT"
Copyright (c) 1999, 2000 by Randal L. Schwartz and Stonehenge
Consulting Services, Inc.  Permission is hereby granted to distribute
this document intact with the Perl distribution, and in accordance
with the licenses of the Perl distribution; derived documents must
include this copyright notice intact.
.PP
Portions of this text have been derived from Perl Training materials
originally appearing in the \fIPackages, References, Objects, and
Modules\fR course taught by instructors for Stonehenge Consulting
Services, Inc. and used with permission.
.PP
Portions of this text have been derived from materials originally
appearing in \fILinux Magazine\fR and used with permission.

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].