📄 perlboot.pod
字号:
Using this simple syntax, we have class methods, (multiple)inheritance, overriding, and extending. Using just what we've seen sofar, we've been able to factor out common code, and provide a nice wayto reuse implementations with variations. This is at the core of whatobjects provide, but objects also provide instance data, which wehaven't even begun to cover.=head2 A horse is a horse, of course of course -- or is it?Let's start with the code for the C<Animal> classand the C<Horse> class: { 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 C<< Horse->speak >> to ripple upward toC<Animal::speak>, calling back to C<Horse::sound> to get the specificsound, and the output of: 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'sgreat for making horses the same, but how do we capture thedistinctions about an individual horse? For example, suppose I wantto give my first horse a name. There's got to be a way to keep itsname 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 referencecan be an instance, so let's start with the simplest referencethat can hold a horse's name: a scalar reference. my $name = "Mr. Ed"; my $talking = \$name;So now C<$talking> is a reference to what will be the instance-specificdata (the name). The final step in turning this into a real instanceis with a special operator called C<bless>: bless $talking, Horse;This operator stores information about the package named C<Horse> intothe thing pointed at by the reference. At this point, we sayC<$talking> is an instance of C<Horse>. That is, it's a specifichorse. The reference is otherwise unchanged, and can still be usedwith traditional dereferencing operators.=head2 Invoking an instance methodThe method arrow can be used on instances, as well as names ofpackages (classes). So, let's get the sound that C<$talking> makes: my $noise = $talking->sound;To invoke C<sound>, Perl first notes that C<$talking> is a blessedreference (and thus an instance). It then constructs an argumentlist, in this case from just C<($talking)>. (Later we'll see thatarguments will take their place following the instance variable,just like with classes.)Now for the fun part: Perl takes the class in which the instance wasblessed, in this case C<Horse>, and uses that to locate the subroutineto invoke the method. In this case, C<Horse::sound> is found directly(without using inheritance), yielding the final subroutine invocation: Horse::sound($talking)Note that the first parameter here is still the instance, not the nameof the class as before. We'll get C<neigh> as the return value, andthat'll end up as the C<$noise> variable above.If Horse::sound had not been found, we'd be wandering up theC<@Horse::ISA> list to try to find the method in one of thesuperclasses, just as for a class method. The only difference betweena class method and an instance method is whether the first parameteris an instance (a blessed reference) or a class name (a string).=head2 Accessing the instance dataBecause we get the instance as the first parameter, we can now accessthe instance-specific data. In this case, let's add a way to get atthe 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 C<Horse::name>, the C<@_> array contains just C<$talking>,which the C<shift> stores into C<$self>. (It's traditional to shiftthe first parameter off into a variable named C<$self> for instancemethods, so stay with that unless you have strong reasons otherwise.)Then, C<$self> gets de-referenced as a scalar ref, yielding C<Mr. Ed>,and we're done with that. The result is: Mr. Ed says neigh.=head2 How to build a horseOf course, if we constructed all of our horses by hand, we'd mostlikely make mistakes from time to time. We're also violating one ofthe properties of object-oriented programming, in that the "insideguts" 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 classbuild 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 C<named> method, we can build a horse: my $talking = Horse->named("Mr. Ed");Notice we're back to a class method, so the two arguments toC<Horse::named> are C<Horse> and C<Mr. Ed>. The C<bless> operatornot only blesses C<$name>, it also returns the reference to C<$name>,so that's fine as a return value. And that's how to build a horse.We've called the constructor C<named> here, so that it quickly denotesthe constructor's argument as the name for this particular C<Horse>.You can use different constructors with different names for differentways of "giving birth" to the object (like maybe recording itspedigree or date of birth). However, you'll find that most peoplecoming to Perl from more limited languages use a single constructornamed C<new>, with various ways of interpreting the arguments toC<new>. Either style is fine, as long as you document your particularway of giving birth to an object. (And you I<were> going to do that,right?)=head2 Inheriting the constructorBut was there anything specific to C<Horse> in that method? No. Therefore,it's also the same recipe for building anything else that inherited fromC<Animal>, so let's put it there: { 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 C<speak> on an instance? my $talking = Horse->named("Mr. Ed"); $talking->speak;We get a debugging value: a Horse=SCALAR(0xaca42ac) goes neigh!Why? Because the C<Animal::speak> routine is expecting a classname asits first parameter, not an instance. When the instance is passed in,we'll end up using a blessed scalar reference as a string, and thatshows up as we saw it just now.=head2 Making a method work with either classes or instancesAll we need is for a method to detect if it is being called on a classor called on an instance. The most straightforward way is with theC<ref> operator. This returns a string (the classname) when used on ablessed reference, and an empty string when used on a string (like aclassname). Let's modify the C<name> method first to notice the change: 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 C<?:> operator comes in handy to select either thedereference or a derived string. Now we can use this with either aninstance or a class. Note that I've changed the first parameterholder to C<$either> to show that this is intended: 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 C<speak> to use this: sub speak { my $either = shift; print $either->name, " goes ", $either->sound, "\n"; }And since C<sound> already worked with either a class or an instance,we're done!=head2 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");=head2 More interesting instancesWhat if an instance needs more data? Most interesting instances aremade of many items, each of which can in turn be a reference or evenanother 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 (oftencalled "instance variables" or "member variables"), and thecorresponding values are, well, the values.But how do we turn the horse into a hash? Recall that an object wasany blessed reference. We can just as easily make it a blessed hashreference as a blessed scalar reference, as long as everything thatlooks 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 C<< $bad->{Name} >> has C<Evil>, and C<< $bad->{Color} >> hasC<black>. But we want to make C<< $bad->name >> access the name, andthat's now messed up because it's expecting a scalar reference. Notto worry, because that's pretty easy to fix up: ## in Animal sub name { my $either = shift; ref $either ? $either->{Name} : "an unnamed $either"; }And of course C<named> still builds a scalar sheep, so let's fix thatas well: ## in Animal sub named { my $class = shift; my $name = shift; my $self = { Name => $name, Color => $class->default_color }; bless $self, $class; }What's this C<default_color>? Well, if C<named> 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: ## 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 C<Animal>: ## in Animal sub default_color { "brown" }Now, because C<name> and C<named> were the only methods thatreferenced the "structure" of the object, the rest of the methods canremain the same, so C<speak> still works as before.=head2 A horse of a different colorBut having all our horses be brown would be boring. So let's add amethod 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: C<$_[0]> is usedin-place, rather than with a C<shift>. (This saves us a bit of timefor something that may be invoked frequently.) And now we can fixthat color for Mr. Ed: 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=head2 SummarySo, now we have class methods, constructors, instance methods,instance data, and even accessors. But that's still just thebeginning of what Perl has to offer. We haven't even begun to talkabout accessors that double as getters and setters, destructors,indirect object notation, subclasses that add instance data, per-classdata, overloading, "isa" and "can" tests, C<UNIVERSAL> class, and soon. That's for the rest of the Perl documentation to cover.Hopefully, this gets you started, though.=head1 SEE ALSOFor more information, see L<perlobj> (for all the gritty details aboutPerl objects, now that you've seen the basics), L<perltoot> (thetutorial for those who already know objects), L<perltooc> (dealingwith class data), L<perlbot> (for some more tricks), and books such asDamian Conway's excellent I<Object Oriented Perl>.Some modules which might prove interesting are Class::Accessor,Class::Class, Class::Contract, Class::Data::Inheritable,Class::MethodMaker and Tie::SecureHash=head1 COPYRIGHTCopyright (c) 1999, 2000 by Randal L. Schwartz and StonehengeConsulting Services, Inc. Permission is hereby granted to distributethis document intact with the Perl distribution, and in accordancewith the licenses of the Perl distribution; derived documents mustinclude this copyright notice intact.Portions of this text have been derived from Perl Training materialsoriginally appearing in the I<Packages, References, Objects, andModules> course taught by instructors for Stonehenge ConsultingServices, Inc. and used with permission.Portions of this text have been derived from materials originallyappearing in I<Linux Magazine> and used with permission.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -