📄 perlobj.1
字号:
.Sh "Method Invocation".IX Xref "invocation method arrow ->".IX Subsection "Method Invocation"For various historical and other reasons, Perl offers two equivalentways to write a method call. The simpler and more common way is to usethe arrow notation:.PP.Vb 2\& my $fred = Critter\->find("Fred");\& $fred\->display("Height", "Weight");.Ve.PPYou should already be familiar with the use of the \f(CW\*(C`\->\*(C'\fR operator withreferences. In fact, since \f(CW$fred\fR above is a reference to an object,you could think of the method call as just another form ofdereferencing..PPWhatever is on the left side of the arrow, whether a reference or aclass name, is passed to the method subroutine as its first argument.So the above code is mostly equivalent to:.PP.Vb 2\& my $fred = Critter::find("Critter", "Fred");\& Critter::display($fred, "Height", "Weight");.Ve.PPHow does Perl know which package the subroutine is in? By looking atthe left side of the arrow, which must be either a package name or areference to an object, i.e. something that has been blessed to apackage. Either way, that's the package where Perl starts looking. Ifthat package has no subroutine with that name, Perl starts looking forit in any base classes of that package, and so on..PPIf you need to, you \fIcan\fR force Perl to start looking in some other package:.PP.Vb 2\& my $barney = MyCritter\->Critter::find("Barney");\& $barney\->Critter::display("Height", "Weight");.Ve.PPHere \f(CW\*(C`MyCritter\*(C'\fR is presumably a subclass of \f(CW\*(C`Critter\*(C'\fR that definesits own versions of \fIfind()\fR and \fIdisplay()\fR. We haven't specified whatthose methods do, but that doesn't matter above since we've forced Perlto start looking for the subroutines in \f(CW\*(C`Critter\*(C'\fR..PPAs a special case of the above, you may use the \f(CW\*(C`SUPER\*(C'\fR pseudo-class totell Perl to start looking for the method in the packages named in thecurrent class's \f(CW@ISA\fR list..IX Xref "SUPER".PP.Vb 2\& package MyCritter;\& use base \*(AqCritter\*(Aq; # sets @MyCritter::ISA = (\*(AqCritter\*(Aq);\&\& sub display { \& my ($self, @args) = @_;\& $self\->SUPER::display("Name", @args);\& }.Ve.PPIt is important to note that \f(CW\*(C`SUPER\*(C'\fR refers to the superclass(es) of the\&\fIcurrent package\fR and not to the superclass(es) of the object. Also, the\&\f(CW\*(C`SUPER\*(C'\fR pseudo-class can only currently be used as a modifier to a methodname, but not in any of the other ways that class names are normally used,eg:.IX Xref "SUPER".PP.Vb 3\& something\->SUPER::method(...); # OK\& SUPER::method(...); # WRONG\& SUPER\->method(...); # WRONG.Ve.PPInstead of a class name or an object reference, you can also use anyexpression that returns either of those on the left side of the arrow.So the following statement is valid:.PP.Vb 1\& Critter\->find("Fred")\->display("Height", "Weight");.Ve.PPand so is the following:.PP.Vb 1\& my $fred = (reverse "rettirC")\->find(reverse "derF");.Ve.PPThe right side of the arrow typically is the method name, but a simple scalar variable containing either the method name or a subroutine reference can also be used..Sh "Indirect Object Syntax".IX Xref "indirect object syntax invocation, indirect indirect".IX Subsection "Indirect Object Syntax"The other way to invoke a method is by using the so-called \*(L"indirectobject\*(R" notation. This syntax was available in Perl 4 long beforeobjects were introduced, and is still used with filehandles like this:.PP.Vb 1\& print STDERR "help!!!\en";.Ve.PPThe same syntax can be used to call either object or class methods..PP.Vb 2\& my $fred = find Critter "Fred";\& display $fred "Height", "Weight";.Ve.PPNotice that there is no comma between the object or class name and theparameters. This is how Perl can tell you want an indirect method callinstead of an ordinary subroutine call..PPBut what if there are no arguments? In that case, Perl must guess whatyou want. Even worse, it must make that guess \fIat compile time\fR.Usually Perl gets it right, but when it doesn't you get a functioncall compiled as a method, or vice versa. This can introduce subtle bugsthat are hard to detect..PPFor example, a call to a method \f(CW\*(C`new\*(C'\fR in indirect notation \*(-- as \*(C+programmers are wont to make \*(-- can be miscompiled into a subroutinecall if there's already a \f(CW\*(C`new\*(C'\fR function in scope. You'd end upcalling the current package's \f(CW\*(C`new\*(C'\fR as a subroutine, rather than thedesired class's method. The compiler tries to cheat by rememberingbareword \f(CW\*(C`require\*(C'\fRs, but the grief when it messes up just isn't worth theyears of debugging it will take you to track down such subtle bugs..PPThere is another problem with this syntax: the indirect object islimited to a name, a scalar variable, or a block, because it would haveto do too much lookahead otherwise, just like any other postfixdereference in the language. (These are the same quirky rules as areused for the filehandle slot in functions like \f(CW\*(C`print\*(C'\fR and \f(CW\*(C`printf\*(C'\fR.)This can lead to horribly confusing precedence problems, as in thesenext two lines:.PP.Vb 2\& move $obj\->{FIELD}; # probably wrong!\& move $ary[$i]; # probably wrong!.Ve.PPThose actually parse as the very surprising:.PP.Vb 2\& $obj\->move\->{FIELD}; # Well, lookee here\& $ary\->move([$i]); # Didn\*(Aqt expect this one, eh?.Ve.PPRather than what you might have expected:.PP.Vb 2\& $obj\->{FIELD}\->move(); # You should be so lucky.\& $ary[$i]\->move; # Yeah, sure..Ve.PPTo get the correct behavior with indirect object syntax, you would haveto use a block around the indirect object:.PP.Vb 2\& move {$obj\->{FIELD}};\& move {$ary[$i]};.Ve.PPEven then, you still have the same potential problem if there happens tobe a function named \f(CW\*(C`move\*(C'\fR in the current package. \fBThe \f(CB\*(C`\->\*(C'\fBnotation suffers from neither of these disturbing ambiguities, so werecommend you use it exclusively.\fR However, you may still end up havingto read code using the indirect object notation, so it's important to befamiliar with it..Sh "Default \s-1UNIVERSAL\s0 methods".IX Xref "UNIVERSAL".IX Subsection "Default UNIVERSAL methods"The \f(CW\*(C`UNIVERSAL\*(C'\fR package automatically contains the following methods thatare inherited by all other classes:.IP "isa(\s-1CLASS\s0)" 4.IX Xref "isa".IX Item "isa(CLASS)"\&\f(CW\*(C`isa\*(C'\fR returns \fItrue\fR if its object is blessed into a subclass of \f(CW\*(C`CLASS\*(C'\fR.SpYou can also call \f(CW\*(C`UNIVERSAL::isa\*(C'\fR as a subroutine with two arguments. Ofcourse, this will do the wrong thing if someone has overridden \f(CW\*(C`isa\*(C'\fR in aclass, so don't do it..SpIf you need to determine whether you've received a valid invocant, use the\&\f(CW\*(C`blessed\*(C'\fR function from Scalar::Util:.IX Xref "invocant blessed".Sp.Vb 3\& if (blessed($ref) && $ref\->isa( \*(AqSome::Class\*(Aq)) {\& # ...\& }.Ve.Sp\&\f(CW\*(C`blessed\*(C'\fR returns the name of the package the argument has beenblessed into, or \f(CW\*(C`undef\*(C'\fR..IP "can(\s-1METHOD\s0)" 4.IX Xref "can".IX Item "can(METHOD)"\&\f(CW\*(C`can\*(C'\fR checks to see if its object has a method called \f(CW\*(C`METHOD\*(C'\fR,if it does then a reference to the sub is returned, if it does not then\&\fIundef\fR is returned..Sp\&\f(CW\*(C`UNIVERSAL::can\*(C'\fR can also be called as a subroutine with two arguments. It'llalways return \fIundef\fR if its first argument isn't an object or a class name.The same caveats for calling \f(CW\*(C`UNIVERSAL::isa\*(C'\fR directly apply here, too..IP "\s-1VERSION\s0( [\s-1NEED\s0] )" 4.IX Xref "VERSION".IX Item "VERSION( [NEED] )"\&\f(CW\*(C`VERSION\*(C'\fR returns the version number of the class (package). If the\&\s-1NEED\s0 argument is given then it will check that the current version (asdefined by the \f(CW$VERSION\fR variable in the given package) not less than\&\s-1NEED\s0; it will die if this is not the case. This method is normallycalled as a class method. This method is called automatically by the\&\f(CW\*(C`VERSION\*(C'\fR form of \f(CW\*(C`use\*(C'\fR..Sp.Vb 3\& use A 1.2 qw(some imported subs);\& # implies:\& A\->VERSION(1.2);.Ve.PP\&\fB\s-1NOTE:\s0\fR \f(CW\*(C`can\*(C'\fR directly uses Perl's internal code for method lookup, and\&\f(CW\*(C`isa\*(C'\fR uses a very similar method and cache-ing strategy. This may causestrange effects if the Perl code dynamically changes \f(CW@ISA\fR in any package..PPYou may add other methods to the \s-1UNIVERSAL\s0 class via Perl or \s-1XS\s0 code.You do not need to \f(CW\*(C`use UNIVERSAL\*(C'\fR to make these methodsavailable to your program (and you should not do so)..Sh "Destructors".IX Xref "destructor DESTROY".IX Subsection "Destructors"When the last reference to an object goes away, the object isautomatically destroyed. (This may even be after you exit, if you'vestored references in global variables.) If you want to capture controljust before the object is freed, you may define a \s-1DESTROY\s0 method inyour class. It will automatically be called at the appropriate moment,and you can do any extra cleanup you need to do. Perl passes a referenceto the object under destruction as the first (and only) argument. Bewarethat the reference is a read-only value, and cannot be modified bymanipulating \f(CW$_[0]\fR within the destructor. The object itself (i.e.the thingy the reference points to, namely \f(CW\*(C`${$_[0]}\*(C'\fR, \f(CW\*(C`@{$_[0]}\*(C'\fR, \&\f(CW\*(C`%{$_[0]}\*(C'\fR etc.) is not similarly constrained..PPSince \s-1DESTROY\s0 methods can be called at unpredictable times, it isimportant that you localise any global variables that the method mayupdate. In particular, localise \f(CW$@\fR if you use \f(CW\*(C`eval {}\*(C'\fR andlocalise \f(CW$?\fR if you use \f(CW\*(C`system\*(C'\fR or backticks..PPIf you arrange to re-bless the reference before the destructor returns,perl will again call the \s-1DESTROY\s0 method for the re-blessed object afterthe current one returns. This can be used for clean delegation ofobject destruction, or for ensuring that destructors in the base classesof your choosing get called. Explicitly calling \s-1DESTROY\s0 is also possible,but is usually never needed..PPDo not confuse the previous discussion with how objects \fI\s-1CONTAINED\s0\fR in the currentone are destroyed. Such objects will be freed and destroyed automaticallywhen the current object is freed, provided no other references to them existelsewhere..Sh "Summary".IX Subsection "Summary"That's about all there is to it. Now you need just to go off and buy abook about object-oriented design methodology, and bang your foreheadwith it for the next six months or so..Sh "Two-Phased Garbage Collection".IX Xref "garbage collection GC circular reference reference, circular DESTROY destructor".IX Subsection "Two-Phased Garbage Collection"For most purposes, Perl uses a fast and simple, reference-basedgarbage collection system. That means there's an extradereference going on at some level, so if you haven't builtyour Perl executable using your C compiler's \f(CW\*(C`\-O\*(C'\fR flag, performancewill suffer. If you \fIhave\fR built Perl with \f(CW\*(C`cc \-O\*(C'\fR, then thisprobably won't matter..PPA more serious concern is that unreachable memory with a non-zeroreference count will not normally get freed. Therefore, this is a badidea:.PP.Vb 4\& {\& my $a;\& $a = \e$a;\& }.Ve.PPEven thought \f(CW$a\fR \fIshould\fR go away, it can't. When building recursive datastructures, you'll have to break the self-reference yourself explicitlyif you don't care to leak. For example, here's a self-referentialnode such as one might use in a sophisticated tree structure:.PP.Vb 7\& sub new_node {\& my $class = shift;\& my $node = {};\& $node\->{LEFT} = $node\->{RIGHT} = $node;\& $node\->{DATA} = [ @_ ];\& return bless $node => $class;\& }.Ve.PPIf you create nodes like that, they (currently) won't go away unless youbreak their self reference yourself. (In other words, this is not to beconstrued as a feature, and you shouldn't depend on it.).PPAlmost..PPWhen an interpreter thread finally shuts down (usually when your programexits), then a rather costly but complete mark-and-sweep style of garbagecollection is performed, and everything allocated by that thread getsdestroyed. This is essential to support Perl as an embedded or amultithreadable language. For example, this program demonstrates Perl'stwo-phased garbage collection:.PP.Vb 2\& #!/usr/bin/perl\& package Subtle;\&\& sub new {\& my $test;\& $test = \e$test;\& warn "CREATING " . \e$test;\& return bless \e$test;\& }\&\& sub DESTROY {\& my $self = shift;\& warn "DESTROYING $self";\& }\&\& package main;\&\& warn "starting program";\& {\& my $a = Subtle\->new;\& my $b = Subtle\->new;\& $$a = 0; # break selfref\& warn "leaving block";\& }\&\& warn "just exited block";\& warn "time to die...";\& exit;.Ve.PPWhen run as \fI/foo/test\fR, the following output is produced:.PP.Vb 8\& starting program at /foo/test line 18.\& CREATING SCALAR(0x8e5b8) at /foo/test line 7.\& CREATING SCALAR(0x8e57c) at /foo/test line 7.\& leaving block at /foo/test line 23.\& DESTROYING Subtle=SCALAR(0x8e5b8) at /foo/test line 13.\& just exited block at /foo/test line 26.\& time to die... at /foo/test line 27.\& DESTROYING Subtle=SCALAR(0x8e57c) during global destruction..Ve.PPNotice that \*(L"global destruction\*(R" bit there? That's the threadgarbage collector reaching the unreachable..PPObjects are always destructed, even when regular refs aren't. Objectsare destructed in a separate pass before ordinary refs just to prevent object destructors from using refs that have been themselvesdestructed. Plain refs are only garbage-collected if the destruct levelis greater than 0. You can test the higher levels of global destructionby setting the \s-1PERL_DESTRUCT_LEVEL\s0 environment variable, presuming\&\f(CW\*(C`\-DDEBUGGING\*(C'\fR was enabled during perl build time.See \*(L"\s-1PERL_DESTRUCT_LEVEL\s0\*(R" in perlhack for more information..PPA more complete garbage collection strategy will be implementedat a future date..PPIn the meantime, the best solution is to create a non-recursive containerclass that holds a pointer to the self-referential data structure.Define a \s-1DESTROY\s0 method for the containing object's class that manuallybreaks the circularities in the self-referential structure..SH "SEE ALSO".IX Header "SEE ALSO"A kinder, gentler tutorial on object-oriented programming in Perl canbe found in perltoot, perlboot and perltooc. You shouldalso check out perlbot for other object tricks, traps, and tips, aswell as perlmodlib for some style guides on constructing bothmodules and classes.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -