NAMEperlboot - Beginner's Object-Oriented Tutorial
DESCRIPTIONIf you're not familiar with objects from other languages, some of the other Perl object documentation may be a little daunting, such as the perlobj manpage, a basic reference in using objects, and the perltoot manpage, which introduces readers to the peculiarities of Perl's object system in a tutorial way. So, let's take a different approach, presuming no prior object experience. It helps if you know about subroutines (the perlsub manpage), references (the perlref manpage et. seq.), and packages (the perlmod manpage), so become familiar with those first if you haven't already.
If we could talk to the animals...Let's let the animals talk for a moment: sub Cow::speak { print "a Cow goes moooo!\n"; } sub Horse::speak { print "a Horse goes neigh!\n"; } sub Sheep::speak { print "a Sheep goes baaaah!\n" } Cow::speak; Horse::speak; Sheep::speak; This results in: a Cow goes moooo! a Horse goes neigh! a Sheep goes baaaah! Nothing spectacular here. Simple subroutines, albeit from separate packages, and called using the full package name. So let's create an entire pasture: # Cow::speak, Horse::speak, Sheep::speak as before @pasture = qw(Cow Cow Horse Sheep Sheep); foreach $animal (@pasture) { &{$animal."::speak"}; } This results in: a Cow goes moooo! a Cow goes moooo! a Horse goes neigh! a Sheep goes baaaah! a Sheep goes baaaah! Wow. That symbolic coderef de-referencing there is pretty nasty.
We're counting on Or is it?
Introducing the method invocation arrowFor now, let's say that # Cow::speak, Horse::speak, Sheep::speak as before Cow->speak; Horse->speak; Sheep->speak; And once again, this results in: a Cow goes moooo! a Horse goes neigh! a Sheep goes baaaah! That's not fun yet. Same number of characters, all constant, no variables. But yet, the parts are separable now. Watch: $a = "Cow"; $a->speak; # invokes Cow->speak 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
Invoking a barnyardLet's take that new arrow invocation and put it back in the barnyard example: sub Cow::speak { print "a Cow goes moooo!\n"; } sub Horse::speak { print "a Horse goes neigh!\n"; } sub Sheep::speak { print "a Sheep goes baaaah!\n" } @pasture = qw(Cow Cow Horse Sheep Sheep); foreach $animal (@pasture) { $animal->speak; } There! Now we have the animals all talking, and safely at that, without the use of symbolic coderefs. But look at all that common code. Each of the 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.
The extra parameter of method invocationThe invocation of: Class->method(@args) attempts to invoke subroutine Class::method("Class", @args); (If the subroutine can't be found, ``inheritance'' 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 sub Sheep::speak { my $class = shift; print "a $class goes baaaah!\n"; } And the other two animals come out similarly: sub Cow::speak { my $class = shift; print "a $class goes moooo!\n"; } sub Horse::speak { my $class = shift; print "a $class goes neigh!\n"; } In each case,
Calling a second method to simplify thingsLet's call out from { package Cow; sub sound { "moooo" } sub speak { my $class = shift; print "a $class goes ", $class->sound, "!\n" } } Now, when we call { package Horse; sub sound { "neigh" } sub speak { my $class = shift; print "a $class goes ", $class->sound, "!\n" } } Only the name of the package and the specific sound change. So can we
somehow share the definition for
Inheriting the windpipesWe'll define a common subroutine package called { package Animal; sub speak { my $class = shift; print "a $class goes ", $class->sound, "!\n" } } Then, for each animal, we say it ``inherits'' from { package Cow; @ISA = qw(Animal); sub sound { "moooo" } } Note the added But what happens when we invoke First, Perl constructs the argument list. In this case, it's just
Perl next checks for Inside the
A few notes about @ISAThis magical If When we turn on The easiest is to just spell the package name out: @Cow::ISA = qw(Animal); Or allow it as an implicitly named package variable: package Cow; use vars qw(@ISA); @ISA = qw(Animal); If you're bringing in the class from outside, via an object-oriented module, you change: package Cow; use Animal; use vars qw(@ISA); @ISA = qw(Animal); into just: package Cow; use base qw(Animal); And that's pretty darn compact.
Overriding the methodsLet's add a mouse, which can barely be heard: # Animal package from before { package Mouse; @ISA = qw(Animal); sub sound { "squeak" } sub speak { my $class = shift; print "a $class goes ", $class->sound, "!\n"; print "[but you can barely hear it!]\n"; } } Mouse->speak; which results in: a Mouse goes squeak! [but you can barely hear it!] Here, But we've now duplicated some of the code from First, we can invoke the # 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!]\n"; } } Note that we have to include the Invoking Also note that the
Starting the search from a different placeA better solution is to tell Perl to search from a higher place in the inheritance chain: # 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!]\n"; } } Ahh. This works. Using this syntax, we start with But this isn't the best solution. We still have to keep the
The SUPER way of doing thingsBy changing the # 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!]\n"; } } So,
Where we're at so far...So far, we've seen the method arrow syntax: Class->method(@args); or the equivalent: $a = "Class"; $a->method(@args); which constructs an argument list of: ("Class", @args) and attempts to invoke Class::method("Class", @Args); However, if 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.
A horse is a horse, of course of course -- or is it?Let's start with the code for the { package Animal; sub speak { my $class = shift; print "a $class goes ", $class->sound, "!\n" } } { package Horse; @ISA = qw(Animal); sub sound { "neigh" } } This lets us invoke a Horse goes neigh! 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. We can do that by drawing a new distinction, called an ``instance''. An ``instance'' 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. my $name = "Mr. Ed"; my $talking = \$name; So now bless $talking, Horse; This operator stores information about the package named
Invoking an instance methodThe method arrow can be used on instances, as well as names of
packages (classes). So, let's get the sound that my $noise = $talking->sound; To invoke Now for the fun part: Perl takes the class in which the instance was
blessed, in this case Horse::sound($talking) Note that the first parameter here is still the instance, not the name
of the class as before. We'll get If Horse::sound had not been found, we'd be wandering up the
Accessing the instance dataBecause 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: { package Horse; @ISA = qw(Animal); sub sound { "neigh" } sub name { my $self = shift; $$self; } } Now we call for the name: print $talking->name, " says ", $talking->sound, "\n"; Inside Mr. Ed says neigh.
How to build a horseOf 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 ``inside guts'' 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: { package Horse; @ISA = qw(Animal); sub sound { "neigh" } sub name { my $self = shift; $$self; } sub named { my $class = shift; my $name = shift; bless \$name, $class; } } Now with the new my $talking = Horse->named("Mr. Ed"); Notice we're back to a class method, so the two arguments to
We've called the constructor
Inheriting the constructorBut was there anything specific to { package Animal; sub speak { my $class = shift; print "a $class goes ", $class->sound, "!\n" } sub name { my $self = shift; $$self; } sub named { my $class = shift; my $name = shift; bless \$name, $class; } } { package Horse; @ISA = qw(Animal); sub sound { "neigh" } } Ahh, but what happens if we invoke my $talking = Horse->named("Mr. Ed"); $talking->speak; We get a debugging value: a Horse=SCALAR(0xaca42ac) goes neigh! Why? Because the
Making a method work with either classes or instancesAll 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
sub name { my $either = shift; ref $either ? $$either # it's an instance, return name : "an unnamed $either"; # it's a class, return generic } Here, the my $talking = Horse->named("Mr. Ed"); print Horse->name, "\n"; # prints "an unnamed Horse\n" print $talking->name, "\n"; # prints "Mr Ed.\n" and now we'll fix sub speak { my $either = shift; print $either->name, " goes ", $either->sound, "\n"; } And since
Adding parameters to a methodLet's train our animals to eat: { package Animal; sub named { my $class = shift; my $name = shift; bless \$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, "\n"; } sub eat { my $either = shift; my $food = shift; print $either->name, " eats $food.\n"; } } { package Horse; @ISA = qw(Animal); sub sound { "neigh" } } { package Sheep; @ISA = qw(Animal); sub sound { "baaaah" } } And now try it out: my $talking = Horse->named("Mr. Ed"); $talking->eat("hay"); Sheep->eat("grass"); which prints: Mr. Ed eats hay. an unnamed Sheep eats grass. An instance method with parameters gets invoked with the instance, and then the list of parameters. So that first invocation is like: Animal::eat($talking, "hay");
More interesting instancesWhat 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 ``instance variables'' or ``member variables''), and the corresponding values are, well, the values. 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. Let's make a sheep that has a name and a color: my $bad = bless { Name => "Evil", Color => "black" }, Sheep; so ## in Animal sub name { my $either = shift; ref $either ? $either->{Name} : "an unnamed $either"; } And of course ## in Animal sub named { my $class = shift; my $name = shift; my $self = { Name => $name, Color => $class->default_color }; bless $self, $class; } What's this ## in Sheep sub default_color { "white" } And then to keep from having to define one for each additional class,
we'll define a ``backstop'' method that serves as the ``default default'',
directly in ## in Animal sub default_color { "brown" } Now, because
A horse of a different colorBut having all our horses be brown would be boring. So let's add a method or two to get and set the color. ## in Animal sub color { $_[0]->{Color} } sub set_color { $_[0]->{Color} = $_[1]; } Note the alternate way of accessing the arguments: my $talking = Horse->named("Mr. Ed"); $talking->set_color("black-and-white"); print $talking->name, " is colored ", $talking->color, "\n"; which results in: Mr. Ed is colored black-and-white
SummarySo, 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, ``isa'' and ``can'' tests,
SEE ALSOFor more information, see the perlobj manpage (for all the gritty details about Perl objects, now that you've seen the basics), the perltoot manpage (the tutorial for those who already know objects), the perltootc manpage (dealing with class data), the perlbot manpage (for some more tricks), and books such as Damian Conway's excellent Object Oriented Perl. Some modules which might prove interesting are Class::Accessor, Class::Class, Class::Contract, Class::Data::Inheritable, Class::MethodMaker and Tie::SecureHash
COPYRIGHTCopyright (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. Portions of this text have been derived from Perl Training materials originally appearing in the Packages, References, Objects, and Modules course taught by instructors for Stonehenge Consulting Services, Inc. and used with permission. Portions of this text have been derived from materials originally appearing in Linux Magazine and used with permission.
|