PageRenderTime 47ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/IronPython_Main/Runtime/Tests/LinqDlrTests/testenv/perl/lib/pod/perlobj.pod

#
Unknown | 566 lines | 428 code | 138 blank | 0 comment | 0 complexity | 9d07aad46bdae0ac59cba157ebd00506 MD5 | raw file
Possible License(s): GPL-2.0, MPL-2.0-no-copyleft-exception, CPL-1.0, CC-BY-SA-3.0, BSD-3-Clause, ISC, AGPL-3.0, LGPL-2.1, Apache-2.0
  1. =head1 NAME
  2. perlobj - Perl objects
  3. =head1 DESCRIPTION
  4. First you need to understand what references are in Perl.
  5. See L<perlref> for that. Second, if you still find the following
  6. reference work too complicated, a tutorial on object-oriented programming
  7. in Perl can be found in L<perltoot> and L<perltootc>.
  8. If you're still with us, then
  9. here are three very simple definitions that you should find reassuring.
  10. =over 4
  11. =item 1.
  12. An object is simply a reference that happens to know which class it
  13. belongs to.
  14. =item 2.
  15. A class is simply a package that happens to provide methods to deal
  16. with object references.
  17. =item 3.
  18. A method is simply a subroutine that expects an object reference (or
  19. a package name, for class methods) as the first argument.
  20. =back
  21. We'll cover these points now in more depth.
  22. =head2 An Object is Simply a Reference
  23. Unlike say C++, Perl doesn't provide any special syntax for
  24. constructors. A constructor is merely a subroutine that returns a
  25. reference to something "blessed" into a class, generally the
  26. class that the subroutine is defined in. Here is a typical
  27. constructor:
  28. package Critter;
  29. sub new { bless {} }
  30. That word C<new> isn't special. You could have written
  31. a construct this way, too:
  32. package Critter;
  33. sub spawn { bless {} }
  34. This might even be preferable, because the C++ programmers won't
  35. be tricked into thinking that C<new> works in Perl as it does in C++.
  36. It doesn't. We recommend that you name your constructors whatever
  37. makes sense in the context of the problem you're solving. For example,
  38. constructors in the Tk extension to Perl are named after the widgets
  39. they create.
  40. One thing that's different about Perl constructors compared with those in
  41. C++ is that in Perl, they have to allocate their own memory. (The other
  42. things is that they don't automatically call overridden base-class
  43. constructors.) The C<{}> allocates an anonymous hash containing no
  44. key/value pairs, and returns it The bless() takes that reference and
  45. tells the object it references that it's now a Critter, and returns
  46. the reference. This is for convenience, because the referenced object
  47. itself knows that it has been blessed, and the reference to it could
  48. have been returned directly, like this:
  49. sub new {
  50. my $self = {};
  51. bless $self;
  52. return $self;
  53. }
  54. You often see such a thing in more complicated constructors
  55. that wish to call methods in the class as part of the construction:
  56. sub new {
  57. my $self = {};
  58. bless $self;
  59. $self->initialize();
  60. return $self;
  61. }
  62. If you care about inheritance (and you should; see
  63. L<perlmodlib/"Modules: Creation, Use, and Abuse">),
  64. then you want to use the two-arg form of bless
  65. so that your constructors may be inherited:
  66. sub new {
  67. my $class = shift;
  68. my $self = {};
  69. bless $self, $class;
  70. $self->initialize();
  71. return $self;
  72. }
  73. Or if you expect people to call not just C<< CLASS->new() >> but also
  74. C<< $obj->new() >>, then use something like this. The initialize()
  75. method used will be of whatever $class we blessed the
  76. object into:
  77. sub new {
  78. my $this = shift;
  79. my $class = ref($this) || $this;
  80. my $self = {};
  81. bless $self, $class;
  82. $self->initialize();
  83. return $self;
  84. }
  85. Within the class package, the methods will typically deal with the
  86. reference as an ordinary reference. Outside the class package,
  87. the reference is generally treated as an opaque value that may
  88. be accessed only through the class's methods.
  89. Although a constructor can in theory re-bless a referenced object
  90. currently belonging to another class, this is almost certainly going
  91. to get you into trouble. The new class is responsible for all
  92. cleanup later. The previous blessing is forgotten, as an object
  93. may belong to only one class at a time. (Although of course it's
  94. free to inherit methods from many classes.) If you find yourself
  95. having to do this, the parent class is probably misbehaving, though.
  96. A clarification: Perl objects are blessed. References are not. Objects
  97. know which package they belong to. References do not. The bless()
  98. function uses the reference to find the object. Consider
  99. the following example:
  100. $a = {};
  101. $b = $a;
  102. bless $a, BLAH;
  103. print "\$b is a ", ref($b), "\n";
  104. This reports $b as being a BLAH, so obviously bless()
  105. operated on the object and not on the reference.
  106. =head2 A Class is Simply a Package
  107. Unlike say C++, Perl doesn't provide any special syntax for class
  108. definitions. You use a package as a class by putting method
  109. definitions into the class.
  110. There is a special array within each package called @ISA, which says
  111. where else to look for a method if you can't find it in the current
  112. package. This is how Perl implements inheritance. Each element of the
  113. @ISA array is just the name of another package that happens to be a
  114. class package. The classes are searched (depth first) for missing
  115. methods in the order that they occur in @ISA. The classes accessible
  116. through @ISA are known as base classes of the current class.
  117. All classes implicitly inherit from class C<UNIVERSAL> as their
  118. last base class. Several commonly used methods are automatically
  119. supplied in the UNIVERSAL class; see L<"Default UNIVERSAL methods"> for
  120. more details.
  121. If a missing method is found in a base class, it is cached
  122. in the current class for efficiency. Changing @ISA or defining new
  123. subroutines invalidates the cache and causes Perl to do the lookup again.
  124. If neither the current class, its named base classes, nor the UNIVERSAL
  125. class contains the requested method, these three places are searched
  126. all over again, this time looking for a method named AUTOLOAD(). If an
  127. AUTOLOAD is found, this method is called on behalf of the missing method,
  128. setting the package global $AUTOLOAD to be the fully qualified name of
  129. the method that was intended to be called.
  130. If none of that works, Perl finally gives up and complains.
  131. If you want to stop the AUTOLOAD inheritance say simply
  132. sub AUTOLOAD;
  133. and the call will die using the name of the sub being called.
  134. Perl classes do method inheritance only. Data inheritance is left up
  135. to the class itself. By and large, this is not a problem in Perl,
  136. because most classes model the attributes of their object using an
  137. anonymous hash, which serves as its own little namespace to be carved up
  138. by the various classes that might want to do something with the object.
  139. The only problem with this is that you can't sure that you aren't using
  140. a piece of the hash that isn't already used. A reasonable workaround
  141. is to prepend your fieldname in the hash with the package name.
  142. sub bump {
  143. my $self = shift;
  144. $self->{ __PACKAGE__ . ".count"}++;
  145. }
  146. =head2 A Method is Simply a Subroutine
  147. Unlike say C++, Perl doesn't provide any special syntax for method
  148. definition. (It does provide a little syntax for method invocation
  149. though. More on that later.) A method expects its first argument
  150. to be the object (reference) or package (string) it is being invoked
  151. on. There are two ways of calling methods, which we'll call class
  152. methods and instance methods.
  153. A class method expects a class name as the first argument. It
  154. provides functionality for the class as a whole, not for any
  155. individual object belonging to the class. Constructors are often
  156. class methods, but see L<perltoot> and L<perltootc> for alternatives.
  157. Many class methods simply ignore their first argument, because they
  158. already know what package they're in and don't care what package
  159. they were invoked via. (These aren't necessarily the same, because
  160. class methods follow the inheritance tree just like ordinary instance
  161. methods.) Another typical use for class methods is to look up an
  162. object by name:
  163. sub find {
  164. my ($class, $name) = @_;
  165. $objtable{$name};
  166. }
  167. An instance method expects an object reference as its first argument.
  168. Typically it shifts the first argument into a "self" or "this" variable,
  169. and then uses that as an ordinary reference.
  170. sub display {
  171. my $self = shift;
  172. my @keys = @_ ? @_ : sort keys %$self;
  173. foreach $key (@keys) {
  174. print "\t$key => $self->{$key}\n";
  175. }
  176. }
  177. =head2 Method Invocation
  178. There are two ways to invoke a method, one of which you're already
  179. familiar with, and the other of which will look familiar. Perl 4
  180. already had an "indirect object" syntax that you use when you say
  181. print STDERR "help!!!\n";
  182. This same syntax can be used to call either class or instance methods.
  183. We'll use the two methods defined above, the class method to lookup
  184. an object reference and the instance method to print out its attributes.
  185. $fred = find Critter "Fred";
  186. display $fred 'Height', 'Weight';
  187. These could be combined into one statement by using a BLOCK in the
  188. indirect object slot:
  189. display {find Critter "Fred"} 'Height', 'Weight';
  190. For C++ fans, there's also a syntax using -> notation that does exactly
  191. the same thing. The parentheses are required if there are any arguments.
  192. $fred = Critter->find("Fred");
  193. $fred->display('Height', 'Weight');
  194. or in one statement,
  195. Critter->find("Fred")->display('Height', 'Weight');
  196. There are times when one syntax is more readable, and times when the
  197. other syntax is more readable. The indirect object syntax is less
  198. cluttered, but it has the same ambiguity as ordinary list operators.
  199. Indirect object method calls are usually parsed using the same rule as list
  200. operators: "If it looks like a function, it is a function". (Presuming
  201. for the moment that you think two words in a row can look like a
  202. function name. C++ programmers seem to think so with some regularity,
  203. especially when the first word is "new".) Thus, the parentheses of
  204. new Critter ('Barney', 1.5, 70)
  205. are assumed to surround ALL the arguments of the method call, regardless
  206. of what comes after. Saying
  207. new Critter ('Bam' x 2), 1.4, 45
  208. would be equivalent to
  209. Critter->new('Bam' x 2), 1.4, 45
  210. which is unlikely to do what you want. Confusingly, however, this
  211. rule applies only when the indirect object is a bareword package name,
  212. not when it's a scalar, a BLOCK, or a C<Package::> qualified package name.
  213. In those cases, the arguments are parsed in the same way as an
  214. indirect object list operator like print, so
  215. new Critter:: ('Bam' x 2), 1.4, 45
  216. is the same as
  217. Critter::->new(('Bam' x 2), 1.4, 45)
  218. For more reasons why the indirect object syntax is ambiguous, see
  219. L<"WARNING"> below.
  220. There are times when you wish to specify which class's method to use.
  221. Here you can call your method as an ordinary subroutine
  222. call, being sure to pass the requisite first argument explicitly:
  223. $fred = MyCritter::find("Critter", "Fred");
  224. MyCritter::display($fred, 'Height', 'Weight');
  225. Unlike method calls, function calls don't consider inheritance. If you wish
  226. merely to specify that Perl should I<START> looking for a method in a
  227. particular package, use an ordinary method call, but qualify the method
  228. name with the package like this:
  229. $fred = Critter->MyCritter::find("Fred");
  230. $fred->MyCritter::display('Height', 'Weight');
  231. If you're trying to control where the method search begins I<and> you're
  232. executing in the class itself, then you may use the SUPER pseudo class,
  233. which says to start looking in your base class's @ISA list without having
  234. to name it explicitly:
  235. $self->SUPER::display('Height', 'Weight');
  236. Please note that the C<SUPER::> construct is meaningful I<only> within the
  237. class.
  238. Sometimes you want to call a method when you don't know the method name
  239. ahead of time. You can use the arrow form, replacing the method name
  240. with a simple scalar variable containing the method name or a
  241. reference to the function.
  242. $method = $fast ? "findfirst" : "findbest";
  243. $fred->$method(@args); # call by name
  244. if ($coderef = $fred->can($parent . "::findbest")) {
  245. $self->$coderef(@args); # call by coderef
  246. }
  247. =head2 WARNING
  248. While indirect object syntax may well be appealing to English speakers and
  249. to C++ programmers, be not seduced! It suffers from two grave problems.
  250. The first problem is that an indirect object is limited to a name,
  251. a scalar variable, or a block, because it would have to do too much
  252. lookahead otherwise, just like any other postfix dereference in the
  253. language. (These are the same quirky rules as are used for the filehandle
  254. slot in functions like C<print> and C<printf>.) This can lead to horribly
  255. confusing precedence problems, as in these next two lines:
  256. move $obj->{FIELD}; # probably wrong!
  257. move $ary[$i]; # probably wrong!
  258. Those actually parse as the very surprising:
  259. $obj->move->{FIELD}; # Well, lookee here
  260. $ary->move([$i]); # Didn't expect this one, eh?
  261. Rather than what you might have expected:
  262. $obj->{FIELD}->move(); # You should be so lucky.
  263. $ary[$i]->move; # Yeah, sure.
  264. The left side of ``->'' is not so limited, because it's an infix operator,
  265. not a postfix operator.
  266. As if that weren't bad enough, think about this: Perl must guess I<at
  267. compile time> whether C<name> and C<move> above are functions or methods.
  268. Usually Perl gets it right, but when it doesn't it, you get a function
  269. call compiled as a method, or vice versa. This can introduce subtle
  270. bugs that are hard to unravel. For example, calling a method C<new>
  271. in indirect notation--as C++ programmers are so wont to do--can
  272. be miscompiled into a subroutine call if there's already a C<new>
  273. function in scope. You'd end up calling the current package's C<new>
  274. as a subroutine, rather than the desired class's method. The compiler
  275. tries to cheat by remembering bareword C<require>s, but the grief if it
  276. messes up just isn't worth the years of debugging it would likely take
  277. you to track such subtle bugs down.
  278. The infix arrow notation using ``C<< -> >>'' doesn't suffer from either
  279. of these disturbing ambiguities, so we recommend you use it exclusively.
  280. =head2 Default UNIVERSAL methods
  281. The C<UNIVERSAL> package automatically contains the following methods that
  282. are inherited by all other classes:
  283. =over 4
  284. =item isa(CLASS)
  285. C<isa> returns I<true> if its object is blessed into a subclass of C<CLASS>
  286. C<isa> is also exportable and can be called as a sub with two arguments. This
  287. allows the ability to check what a reference points to. Example
  288. use UNIVERSAL qw(isa);
  289. if(isa($ref, 'ARRAY')) {
  290. #...
  291. }
  292. =item can(METHOD)
  293. C<can> checks to see if its object has a method called C<METHOD>,
  294. if it does then a reference to the sub is returned, if it does not then
  295. I<undef> is returned.
  296. =item VERSION( [NEED] )
  297. C<VERSION> returns the version number of the class (package). If the
  298. NEED argument is given then it will check that the current version (as
  299. defined by the $VERSION variable in the given package) not less than
  300. NEED; it will die if this is not the case. This method is normally
  301. called as a class method. This method is called automatically by the
  302. C<VERSION> form of C<use>.
  303. use A 1.2 qw(some imported subs);
  304. # implies:
  305. A->VERSION(1.2);
  306. =back
  307. B<NOTE:> C<can> directly uses Perl's internal code for method lookup, and
  308. C<isa> uses a very similar method and cache-ing strategy. This may cause
  309. strange effects if the Perl code dynamically changes @ISA in any package.
  310. You may add other methods to the UNIVERSAL class via Perl or XS code.
  311. You do not need to C<use UNIVERSAL> to make these methods
  312. available to your program. This is necessary only if you wish to
  313. have C<isa> available as a plain subroutine in the current package.
  314. =head2 Destructors
  315. When the last reference to an object goes away, the object is
  316. automatically destroyed. (This may even be after you exit, if you've
  317. stored references in global variables.) If you want to capture control
  318. just before the object is freed, you may define a DESTROY method in
  319. your class. It will automatically be called at the appropriate moment,
  320. and you can do any extra cleanup you need to do. Perl passes a reference
  321. to the object under destruction as the first (and only) argument. Beware
  322. that the reference is a read-only value, and cannot be modified by
  323. manipulating C<$_[0]> within the destructor. The object itself (i.e.
  324. the thingy the reference points to, namely C<${$_[0]}>, C<@{$_[0]}>,
  325. C<%{$_[0]}> etc.) is not similarly constrained.
  326. If you arrange to re-bless the reference before the destructor returns,
  327. perl will again call the DESTROY method for the re-blessed object after
  328. the current one returns. This can be used for clean delegation of
  329. object destruction, or for ensuring that destructors in the base classes
  330. of your choosing get called. Explicitly calling DESTROY is also possible,
  331. but is usually never needed.
  332. Do not confuse the previous discussion with how objects I<CONTAINED> in the current
  333. one are destroyed. Such objects will be freed and destroyed automatically
  334. when the current object is freed, provided no other references to them exist
  335. elsewhere.
  336. =head2 Summary
  337. That's about all there is to it. Now you need just to go off and buy a
  338. book about object-oriented design methodology, and bang your forehead
  339. with it for the next six months or so.
  340. =head2 Two-Phased Garbage Collection
  341. For most purposes, Perl uses a fast and simple, reference-based
  342. garbage collection system. That means there's an extra
  343. dereference going on at some level, so if you haven't built
  344. your Perl executable using your C compiler's C<-O> flag, performance
  345. will suffer. If you I<have> built Perl with C<cc -O>, then this
  346. probably won't matter.
  347. A more serious concern is that unreachable memory with a non-zero
  348. reference count will not normally get freed. Therefore, this is a bad
  349. idea:
  350. {
  351. my $a;
  352. $a = \$a;
  353. }
  354. Even thought $a I<should> go away, it can't. When building recursive data
  355. structures, you'll have to break the self-reference yourself explicitly
  356. if you don't care to leak. For example, here's a self-referential
  357. node such as one might use in a sophisticated tree structure:
  358. sub new_node {
  359. my $self = shift;
  360. my $class = ref($self) || $self;
  361. my $node = {};
  362. $node->{LEFT} = $node->{RIGHT} = $node;
  363. $node->{DATA} = [ @_ ];
  364. return bless $node => $class;
  365. }
  366. If you create nodes like that, they (currently) won't go away unless you
  367. break their self reference yourself. (In other words, this is not to be
  368. construed as a feature, and you shouldn't depend on it.)
  369. Almost.
  370. When an interpreter thread finally shuts down (usually when your program
  371. exits), then a rather costly but complete mark-and-sweep style of garbage
  372. collection is performed, and everything allocated by that thread gets
  373. destroyed. This is essential to support Perl as an embedded or a
  374. multithreadable language. For example, this program demonstrates Perl's
  375. two-phased garbage collection:
  376. #!/usr/bin/perl
  377. package Subtle;
  378. sub new {
  379. my $test;
  380. $test = \$test;
  381. warn "CREATING " . \$test;
  382. return bless \$test;
  383. }
  384. sub DESTROY {
  385. my $self = shift;
  386. warn "DESTROYING $self";
  387. }
  388. package main;
  389. warn "starting program";
  390. {
  391. my $a = Subtle->new;
  392. my $b = Subtle->new;
  393. $$a = 0; # break selfref
  394. warn "leaving block";
  395. }
  396. warn "just exited block";
  397. warn "time to die...";
  398. exit;
  399. When run as F</tmp/test>, the following output is produced:
  400. starting program at /tmp/test line 18.
  401. CREATING SCALAR(0x8e5b8) at /tmp/test line 7.
  402. CREATING SCALAR(0x8e57c) at /tmp/test line 7.
  403. leaving block at /tmp/test line 23.
  404. DESTROYING Subtle=SCALAR(0x8e5b8) at /tmp/test line 13.
  405. just exited block at /tmp/test line 26.
  406. time to die... at /tmp/test line 27.
  407. DESTROYING Subtle=SCALAR(0x8e57c) during global destruction.
  408. Notice that "global destruction" bit there? That's the thread
  409. garbage collector reaching the unreachable.
  410. Objects are always destructed, even when regular refs aren't. Objects
  411. are destructed in a separate pass before ordinary refs just to
  412. prevent object destructors from using refs that have been themselves
  413. destructed. Plain refs are only garbage-collected if the destruct level
  414. is greater than 0. You can test the higher levels of global destruction
  415. by setting the PERL_DESTRUCT_LEVEL environment variable, presuming
  416. C<-DDEBUGGING> was enabled during perl build time.
  417. A more complete garbage collection strategy will be implemented
  418. at a future date.
  419. In the meantime, the best solution is to create a non-recursive container
  420. class that holds a pointer to the self-referential data structure.
  421. Define a DESTROY method for the containing object's class that manually
  422. breaks the circularities in the self-referential structure.
  423. =head1 SEE ALSO
  424. A kinder, gentler tutorial on object-oriented programming in Perl can
  425. be found in L<perltoot>, L<perlbootc> and L<perltootc>. You should
  426. also check out L<perlbot> for other object tricks, traps, and tips, as
  427. well as L<perlmodlib> for some style guides on constructing both
  428. modules and classes.