📄 perlobj.1
字号:
.\" Automatically generated by Pod::Man 2.16 (Pod::Simple 3.05).\".\" 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. \*(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-.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\}.\".\" Escape single quotes in literal strings from groff's Unicode transform..ie \n(.g .ds Aq \(aq.el .ds Aq '.\".\" 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..ie \nF \{\. de IX. tm Index:\\$1\t\\n%\t"\\$2"... nr % 0. rr F.\}.el \{\. de IX...\}.\".\" 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 "2007-12-18" "perl v5.10.0" "Perl Programmers Reference Guide".\" For nroff, turn off justification. Always turn off hyphenation; it makes.\" way too many mistakes in technical documents..if n .ad l.nh.SH "NAME"perlobj \- Perl objects.IX Xref "object OOP".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 followingreference work too complicated, a tutorial on object-oriented programmingin Perl can be found in perltoot and perltooc..PPIf you're still with us, thenhere are three very simple definitions that you should find reassuring..IP "1." 4An object is simply a reference that happens to know which class itbelongs to..IP "2." 4A class is simply a package that happens to provide methods to dealwith object references..IP "3." 4A method is simply a subroutine that expects an object reference (ora package name, for class methods) as the first argument..PPWe'll cover these points now in more depth..Sh "An Object is Simply a Reference".IX Xref "object bless constructor new".IX Subsection "An Object is Simply a Reference"Unlike say \*(C+, Perl doesn't provide any special syntax forconstructors. A constructor is merely a subroutine that returns areference to something \*(L"blessed\*(R" into a class, generally theclass that the subroutine is defined in. Here is a typicalconstructor:.PP.Vb 2\& package Critter;\& sub new { bless {} }.Ve.PPThat word \f(CW\*(C`new\*(C'\fR isn't special. You could have writtena construct this way, too:.PP.Vb 2\& package Critter;\& sub spawn { bless {} }.Ve.PPThis might even be preferable, because the \*(C+ programmers won'tbe 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 whatevermakes sense in the context of the problem you're solving. For example,constructors in the Tk extension to Perl are named after the widgetsthey create..PPOne thing that's different about Perl constructors compared with those in\&\*(C+ is that in Perl, they have to allocate their own memory. (The otherthings is that they don't automatically call overridden base-classconstructors.) The \f(CW\*(C`{}\*(C'\fR allocates an anonymous hash containing nokey/value pairs, and returns it The \fIbless()\fR takes that reference andtells the object it references that it's now a Critter, and returnsthe reference. This is for convenience, because the referenced objectitself knows that it has been blessed, and the reference to it couldhave been returned directly, like this:.PP.Vb 5\& sub new {\& my $self = {};\& bless $self;\& return $self;\& }.Ve.PPYou often see such a thing in more complicated constructorsthat 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.PPIf 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 blessso that your constructors may be inherited:.PP.Vb 7\& sub new {\& my $class = shift;\& my $self = {};\& bless $self, $class;\& $self\->initialize();\& return $self;\& }.Ve.PPOr 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 the following. (Note that usingthis to call \fInew()\fR on an instance does not automatically perform anycopying. If you want a shallow or deep copy of an object, you'll have tospecifically allow for that.) The \fIinitialize()\fR method used will be ofwhatever \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.PPWithin the class package, the methods will typically deal with thereference as an ordinary reference. Outside the class package,the reference is generally treated as an opaque value that maybe accessed only through the class's methods..PPAlthough a constructor can in theory re-bless a referenced objectcurrently belonging to another class, this is almost certainly goingto get you into trouble. The new class is responsible for allcleanup later. The previous blessing is forgotten, as an objectmay belong to only one class at a time. (Although of course it'sfree to inherit methods from many classes.) If you find yourselfhaving to do this, the parent class is probably misbehaving, though..PPA clarification: Perl objects are blessed. References are not. Objectsknow which package they belong to. References do not. The \fIbless()\fRfunction uses the reference to find the object. Considerthe following example:.PP.Vb 4\& $a = {};\& $b = $a;\& bless $a, BLAH;\& print "\e$b is a ", ref($b), "\en";.Ve.PPThis reports \f(CW$b\fR as being a \s-1BLAH\s0, so obviously \fIbless()\fRoperated on the object and not on the reference..Sh "A Class is Simply a Package".IX Xref "class package @ISA inheritance".IX Subsection "A Class is Simply a Package"Unlike say \*(C+, Perl doesn't provide any special syntax for classdefinitions. You use a package as a class by putting methoddefinitions into the class..PPThere is a special array within each package called \f(CW@ISA\fR, which sayswhere else to look for a method if you can't find it in the currentpackage. 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 aclass package. The classes are searched for missing methods indepth-first, left-to-right order by default (see mro for alternativesearch order and other in-depth information). The classes accessiblethrough \f(CW@ISA\fR are known as base classes of the current class..PPAll classes implicitly inherit from class \f(CW\*(C`UNIVERSAL\*(C'\fR as theirlast base class. Several commonly used methods are automaticallysupplied in the \s-1UNIVERSAL\s0 class; see \*(L"Default \s-1UNIVERSAL\s0 methods\*(R" formore details..IX Xref "UNIVERSAL base class class, base".PPIf a missing method is found in a base class, it is cachedin the current class for efficiency. Changing \f(CW@ISA\fR or defining newsubroutines invalidates the cache and causes Perl to do the lookup again..PPIf neither the current class, its named base classes, nor the \s-1UNIVERSAL\s0class contains the requested method, these three places are searchedall 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 ofthe method that was intended to be called..IX Xref "AUTOLOAD".PPIf none of that works, Perl finally gives up and complains..PPIf you want to stop the \s-1AUTOLOAD\s0 inheritance say simply.IX Xref "AUTOLOAD".PP.Vb 1\& sub AUTOLOAD;.Ve.PPand the call will die using the name of the sub being called..PPPerl classes do method inheritance only. Data inheritance is left upto the class itself. By and large, this is not a problem in Perl,because most classes model the attributes of their object using ananonymous hash, which serves as its own little namespace to be carved upby 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 usinga piece of the hash that isn't already used. A reasonable workaroundis to prepend your fieldname in the hash with the package name..IX Xref "inheritance, method inheritance, data".PP.Vb 4\& sub bump {\& my $self = shift;\& $self\->{ _\|_PACKAGE_\|_ . ".count"}++;\& }.Ve.Sh "A Method is Simply a Subroutine".IX Xref "method".IX Subsection "A Method is Simply a Subroutine"Unlike say \*(C+, Perl doesn't provide any special syntax for methoddefinition. (It does provide a little syntax for method invocationthough. More on that later.) A method expects its first argumentto be the object (reference) or package (string) it is being invokedon. There are two ways of calling methods, which we'll call classmethods and instance methods..PPA class method expects a class name as the first argument. Itprovides functionality for the class as a whole, not for anyindividual object belonging to the class. Constructors are oftenclass methods, but see perltoot and perltooc for alternatives.Many class methods simply ignore their first argument, because theyalready know what package they're in and don't care what packagethey were invoked via. (These aren't necessarily the same, becauseclass methods follow the inheritance tree just like ordinary instancemethods.) Another typical use for class methods is to look up anobject by name:.PP.Vb 4\& sub find {\& my ($class, $name) = @_;\& $objtable{$name};\& }.Ve.PPAn 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
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -