⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 perlboot.1

📁 视频监控网络部分的协议ddns,的模块的实现代码,请大家大胆指正.
💻 1
📖 第 1 页 / 共 3 页
字号:
\&    sub name {\&      my $self = shift;\&      $$self;\&    }\&  }.Ve.PPNow we call for the name:.PP.Vb 1\&  print $talking\->name, " says ", $talking\->sound, "\en";.Ve.PPInside \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 shiftthe first parameter off into a variable named \f(CW$self\fR for instancemethods, 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 mostlikely make mistakes from time to time.  We're also violating one ofthe properties of object-oriented programming, in that the \*(L"insideguts\*(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 classbuild a new horse:.PP.Vb 10\&  { 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.PPNow 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.PPNotice 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 operatornot 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..PPWe've called the constructor \f(CW\*(C`named\*(C'\fR here, so that it quickly denotesthe constructor's argument as the name for this particular \f(CW\*(C`Horse\*(C'\fR.You can use different constructors with different names for differentways of \*(L"giving birth\*(R" 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 \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 particularway 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 10\&  { 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.PPAhh, 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.PPWe get a debugging value:.PP.Vb 1\&  a Horse=SCALAR(0xaca42ac) goes neigh!.Ve.PPWhy?  Because the \f(CW\*(C`Animal::speak\*(C'\fR 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..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 classor 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 ablessed reference, and an empty string when used on a string (like aclassname).  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\*(Aqs an instance, return name\&      : "an unnamed $either"; # it\*(Aqs a class, return generic\&  }.Ve.PPHere, the \f(CW\*(C`?:\*(C'\fR 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 \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.PPand 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.PPAnd 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 10\&  { package Animal;\&    sub named {\&      my $class = shift;\&      my $name = shift;\&      bless \e$name, $class;\&    }\&    sub name {\&      my $either = shift;\&      ref $either\&        ? $$either # it\*(Aqs an instance, return name\&        : "an unnamed $either"; # it\*(Aqs 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.PPAnd now try it out:.PP.Vb 3\&  my $talking = Horse\->named("Mr. Ed");\&  $talking\->eat("hay");\&  Sheep\->eat("grass");.Ve.PPwhich prints:.PP.Vb 2\&  Mr. Ed eats hay.\&  an unnamed Sheep eats grass..Ve.PPAn 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 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 \*(L"instance variables\*(R" or \*(L"member variables\*(R"), and thecorresponding values are, well, the values..PPBut 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..PPLet's make a sheep that has a name and a color:.PP.Vb 1\&  my $bad = bless { Name => "Evil", Color => "black" }, Sheep;.Ve.PPso \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, andthat's now messed up because it's expecting a scalar reference.  Notto 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.PPAnd of course \f(CW\*(C`named\*(C'\fR still builds a scalar sheep, so let's fix thatas 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.PPWhat'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.PPAnd 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.PPNow, because \f(CW\*(C`name\*(C'\fR and \f(CW\*(C`named\*(C'\fR were the only methods thatreferenced the \*(L"structure\*(R" of the object, the rest of the methods canremain 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 amethod or two to get and set the color..PP.Vb 7\&  ## in Animal\&  sub color {\&    $_[0]\->{Color}\&  }\&  sub set_color {\&    $_[0]\->{Color} = $_[1];\&  }.Ve.PPNote the alternate way of accessing the arguments: \f(CW$_[0]\fR is usedin-place, rather than with a \f(CW\*(C`shift\*(C'\fR.  (This saves us a bit of timefor something that may be invoked frequently.)  And now we can fixthat 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.PPwhich 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 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, \*(L"isa\*(R" and \*(L"can\*(R" tests, \f(CW\*(C`UNIVERSAL\*(C'\fR class, and soon.  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 aboutPerl objects, now that you've seen the basics), perltoot (thetutorial for those who already know objects), perltooc (dealingwith class data), perlbot (for some more tricks), and books such asDamian Conway's excellent \fIObject Oriented Perl\fR..PPSome 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 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..PPPortions of this text have been derived from Perl Training materialsoriginally appearing in the \fIPackages, References, Objects, andModules\fR course taught by instructors for Stonehenge ConsultingServices, Inc. and used with permission..PPPortions of this text have been derived from materials originallyappearing in \fILinux Magazine\fR and used with permission.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -