📄 perlobj.pod
字号:
SUPER::method(...); # WRONG SUPER->method(...); # WRONGInstead 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: Critter->find("Fred")->display("Height", "Weight");and so is the following: my $fred = (reverse "rettirC")->find(reverse "derF");The 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.=head2 Indirect Object SyntaxX<indirect object syntax> X<invocation, indirect> X<indirect>The other way to invoke a method is by using the so-called "indirectobject" notation. This syntax was available in Perl 4 long beforeobjects were introduced, and is still used with filehandles like this: print STDERR "help!!!\n";The same syntax can be used to call either object or class methods. my $fred = find Critter "Fred"; display $fred "Height", "Weight";Notice 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.But what if there are no arguments? In that case, Perl must guess whatyou want. Even worse, it must make that guess I<at compile time>.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.For example, a call to a method C<new> in indirect notation -- as C++programmers are wont to make -- can be miscompiled into a subroutinecall if there's already a C<new> function in scope. You'd end upcalling the current package's C<new> as a subroutine, rather than thedesired class's method. The compiler tries to cheat by rememberingbareword C<require>s, but the grief when it messes up just isn't worth theyears of debugging it will take you to track down such subtle bugs.There 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 C<print> and C<printf>.)This can lead to horribly confusing precedence problems, as in thesenext two lines: move $obj->{FIELD}; # probably wrong! move $ary[$i]; # probably wrong!Those actually parse as the very surprising: $obj->move->{FIELD}; # Well, lookee here $ary->move([$i]); # Didn't expect this one, eh?Rather than what you might have expected: $obj->{FIELD}->move(); # You should be so lucky. $ary[$i]->move; # Yeah, sure.To get the correct behavior with indirect object syntax, you would haveto use a block around the indirect object: move {$obj->{FIELD}}; move {$ary[$i]};Even then, you still have the same potential problem if there happens tobe a function named C<move> in the current package. B<The C<< -> >>notation suffers from neither of these disturbing ambiguities, so werecommend you use it exclusively.> However, you may still end up havingto read code using the indirect object notation, so it's important to befamiliar with it.=head2 Default UNIVERSAL methodsX<UNIVERSAL>The C<UNIVERSAL> package automatically contains the following methods thatare inherited by all other classes:=over 4=item isa(CLASS)X<isa>C<isa> returns I<true> if its object is blessed into a subclass of C<CLASS>You can also call C<UNIVERSAL::isa> as a subroutine with two arguments. Ofcourse, this will do the wrong thing if someone has overridden C<isa> in aclass, so don't do it.If you need to determine whether you've received a valid invocant, use theC<blessed> function from L<Scalar::Util>:X<invocant> X<blessed> if (blessed($ref) && $ref->isa( 'Some::Class')) { # ... }C<blessed> returns the name of the package the argument has beenblessed into, or C<undef>.=item can(METHOD)X<can>C<can> checks to see if its object has a method called C<METHOD>,if it does then a reference to the sub is returned, if it does not thenI<undef> is returned.C<UNIVERSAL::can> can also be called as a subroutine with two arguments. It'llalways return I<undef> if its first argument isn't an object or a class name.The same caveats for calling C<UNIVERSAL::isa> directly apply here, too.=item VERSION( [NEED] )X<VERSION>C<VERSION> returns the version number of the class (package). If theNEED argument is given then it will check that the current version (asdefined by the $VERSION variable in the given package) not less thanNEED; it will die if this is not the case. This method is normallycalled as a class method. This method is called automatically by theC<VERSION> form of C<use>. use A 1.2 qw(some imported subs); # implies: A->VERSION(1.2);=backB<NOTE:> C<can> directly uses Perl's internal code for method lookup, andC<isa> uses a very similar method and cache-ing strategy. This may causestrange effects if the Perl code dynamically changes @ISA in any package.You may add other methods to the UNIVERSAL class via Perl or XS code.You do not need to C<use UNIVERSAL> to make these methodsavailable to your program (and you should not do so).=head2 DestructorsX<destructor> X<DESTROY>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 DESTROY 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 C<$_[0]> within the destructor. The object itself (i.e.the thingy the reference points to, namely C<${$_[0]}>, C<@{$_[0]}>, C<%{$_[0]}> etc.) is not similarly constrained.Since DESTROY methods can be called at unpredictable times, it isimportant that you localise any global variables that the method mayupdate. In particular, localise C<$@> if you use C<eval {}> andlocalise C<$?> if you use C<system> or backticks.If you arrange to re-bless the reference before the destructor returns,perl will again call the DESTROY 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 DESTROY is also possible,but is usually never needed.Do not confuse the previous discussion with how objects I<CONTAINED> 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.=head2 SummaryThat'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.=head2 Two-Phased Garbage CollectionX<garbage collection> X<GC> X<circular reference>X<reference, circular> X<DESTROY> X<destructor>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 C<-O> flag, performancewill suffer. If you I<have> built Perl with C<cc -O>, then thisprobably won't matter.A more serious concern is that unreachable memory with a non-zeroreference count will not normally get freed. Therefore, this is a badidea: { my $a; $a = \$a; }Even thought $a I<should> 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: sub new_node { my $class = shift; my $node = {}; $node->{LEFT} = $node->{RIGHT} = $node; $node->{DATA} = [ @_ ]; return bless $node => $class; }If 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.)Almost.When 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: #!/usr/bin/perl package Subtle; sub new { my $test; $test = \$test; warn "CREATING " . \$test; return bless \$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;When run as F</foo/test>, the following output is produced: 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.Notice that "global destruction" bit there? That's the threadgarbage collector reaching the unreachable.Objects 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 PERL_DESTRUCT_LEVEL environment variable, presumingC<-DDEBUGGING> was enabled during perl build time.See L<perlhack/PERL_DESTRUCT_LEVEL> for more information.A more complete garbage collection strategy will be implementedat a future date.In the meantime, the best solution is to create a non-recursive containerclass that holds a pointer to the self-referential data structure.Define a DESTROY method for the containing object's class that manuallybreaks the circularities in the self-referential structure.=head1 SEE ALSOA kinder, gentler tutorial on object-oriented programming in Perl canbe found in L<perltoot>, L<perlboot> and L<perltooc>. You shouldalso check out L<perlbot> for other object tricks, traps, and tips, aswell as L<perlmodlib> for some style guides on constructing bothmodules and classes.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -