Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1798 lines
68 KiB

  1. =head1 NAME
  2. perltoot - Tom's object-oriented tutorial for perl
  3. =head1 DESCRIPTION
  4. Object-oriented programming is a big seller these days. Some managers
  5. would rather have objects than sliced bread. Why is that? What's so
  6. special about an object? Just what I<is> an object anyway?
  7. An object is nothing but a way of tucking away complex behaviours into
  8. a neat little easy-to-use bundle. (This is what professors call
  9. abstraction.) Smart people who have nothing to do but sit around for
  10. weeks on end figuring out really hard problems make these nifty
  11. objects that even regular people can use. (This is what professors call
  12. software reuse.) Users (well, programmers) can play with this little
  13. bundle all they want, but they aren't to open it up and mess with the
  14. insides. Just like an expensive piece of hardware, the contract says
  15. that you void the warranty if you muck with the cover. So don't do that.
  16. The heart of objects is the class, a protected little private namespace
  17. full of data and functions. A class is a set of related routines that
  18. addresses some problem area. You can think of it as a user-defined type.
  19. The Perl package mechanism, also used for more traditional modules,
  20. is used for class modules as well. Objects "live" in a class, meaning
  21. that they belong to some package.
  22. More often than not, the class provides the user with little bundles.
  23. These bundles are objects. They know whose class they belong to,
  24. and how to behave. Users ask the class to do something, like "give
  25. me an object." Or they can ask one of these objects to do something.
  26. Asking a class to do something for you is calling a I<class method>.
  27. Asking an object to do something for you is calling an I<object method>.
  28. Asking either a class (usually) or an object (sometimes) to give you
  29. back an object is calling a I<constructor>, which is just a
  30. kind of method.
  31. That's all well and good, but how is an object different from any other
  32. Perl data type? Just what is an object I<really>; that is, what's its
  33. fundamental type? The answer to the first question is easy. An object
  34. is different from any other data type in Perl in one and only one way:
  35. you may dereference it using not merely string or numeric subscripts
  36. as with simple arrays and hashes, but with named subroutine calls.
  37. In a word, with I<methods>.
  38. The answer to the second question is that it's a reference, and not just
  39. any reference, mind you, but one whose referent has been I<bless>()ed
  40. into a particular class (read: package). What kind of reference? Well,
  41. the answer to that one is a bit less concrete. That's because in Perl
  42. the designer of the class can employ any sort of reference they'd like
  43. as the underlying intrinsic data type. It could be a scalar, an array,
  44. or a hash reference. It could even be a code reference. But because
  45. of its inherent flexibility, an object is usually a hash reference.
  46. =head1 Creating a Class
  47. Before you create a class, you need to decide what to name it. That's
  48. because the class (package) name governs the name of the file used to
  49. house it, just as with regular modules. Then, that class (package)
  50. should provide one or more ways to generate objects. Finally, it should
  51. provide mechanisms to allow users of its objects to indirectly manipulate
  52. these objects from a distance.
  53. For example, let's make a simple Person class module. It gets stored in
  54. the file Person.pm. If it were called a Happy::Person class, it would
  55. be stored in the file Happy/Person.pm, and its package would become
  56. Happy::Person instead of just Person. (On a personal computer not
  57. running Unix or Plan 9, but something like MacOS or VMS, the directory
  58. separator may be different, but the principle is the same.) Do not assume
  59. any formal relationship between modules based on their directory names.
  60. This is merely a grouping convenience, and has no effect on inheritance,
  61. variable accessibility, or anything else.
  62. For this module we aren't going to use Exporter, because we're
  63. a well-behaved class module that doesn't export anything at all.
  64. In order to manufacture objects, a class needs to have a I<constructor
  65. method>. A constructor gives you back not just a regular data type,
  66. but a brand-new object in that class. This magic is taken care of by
  67. the bless() function, whose sole purpose is to enable its referent to
  68. be used as an object. Remember: being an object really means nothing
  69. more than that methods may now be called against it.
  70. While a constructor may be named anything you'd like, most Perl
  71. programmers seem to like to call theirs new(). However, new() is not
  72. a reserved word, and a class is under no obligation to supply such.
  73. Some programmers have also been known to use a function with
  74. the same name as the class as the constructor.
  75. =head2 Object Representation
  76. By far the most common mechanism used in Perl to represent a Pascal
  77. record, a C struct, or a C++ class is an anonymous hash. That's because a
  78. hash has an arbitrary number of data fields, each conveniently accessed by
  79. an arbitrary name of your own devising.
  80. If you were just doing a simple
  81. struct-like emulation, you would likely go about it something like this:
  82. $rec = {
  83. name => "Jason",
  84. age => 23,
  85. peers => [ "Norbert", "Rhys", "Phineas"],
  86. };
  87. If you felt like it, you could add a bit of visual distinction
  88. by up-casing the hash keys:
  89. $rec = {
  90. NAME => "Jason",
  91. AGE => 23,
  92. PEERS => [ "Norbert", "Rhys", "Phineas"],
  93. };
  94. And so you could get at C<< $rec->{NAME} >> to find "Jason", or
  95. C<< @{ $rec->{PEERS} } >> to get at "Norbert", "Rhys", and "Phineas".
  96. (Have you ever noticed how many 23-year-old programmers seem to
  97. be named "Jason" these days? :-)
  98. This same model is often used for classes, although it is not considered
  99. the pinnacle of programming propriety for folks from outside the
  100. class to come waltzing into an object, brazenly accessing its data
  101. members directly. Generally speaking, an object should be considered
  102. an opaque cookie that you use I<object methods> to access. Visually,
  103. methods look like you're dereffing a reference using a function name
  104. instead of brackets or braces.
  105. =head2 Class Interface
  106. Some languages provide a formal syntactic interface to a class's methods,
  107. but Perl does not. It relies on you to read the documentation of each
  108. class. If you try to call an undefined method on an object, Perl won't
  109. complain, but the program will trigger an exception while it's running.
  110. Likewise, if you call a method expecting a prime number as its argument
  111. with a non-prime one instead, you can't expect the compiler to catch this.
  112. (Well, you can expect it all you like, but it's not going to happen.)
  113. Let's suppose you have a well-educated user of your Person class,
  114. someone who has read the docs that explain the prescribed
  115. interface. Here's how they might use the Person class:
  116. use Person;
  117. $him = Person->new();
  118. $him->name("Jason");
  119. $him->age(23);
  120. $him->peers( "Norbert", "Rhys", "Phineas" );
  121. push @All_Recs, $him; # save object in array for later
  122. printf "%s is %d years old.\n", $him->name, $him->age;
  123. print "His peers are: ", join(", ", $him->peers), "\n";
  124. printf "Last rec's name is %s\n", $All_Recs[-1]->name;
  125. As you can see, the user of the class doesn't know (or at least, has no
  126. business paying attention to the fact) that the object has one particular
  127. implementation or another. The interface to the class and its objects
  128. is exclusively via methods, and that's all the user of the class should
  129. ever play with.
  130. =head2 Constructors and Instance Methods
  131. Still, I<someone> has to know what's in the object. And that someone is
  132. the class. It implements methods that the programmer uses to access
  133. the object. Here's how to implement the Person class using the standard
  134. hash-ref-as-an-object idiom. We'll make a class method called new() to
  135. act as the constructor, and three object methods called name(), age(), and
  136. peers() to get at per-object data hidden away in our anonymous hash.
  137. package Person;
  138. use strict;
  139. ##################################################
  140. ## the object constructor (simplistic version) ##
  141. ##################################################
  142. sub new {
  143. my $self = {};
  144. $self->{NAME} = undef;
  145. $self->{AGE} = undef;
  146. $self->{PEERS} = [];
  147. bless($self); # but see below
  148. return $self;
  149. }
  150. ##############################################
  151. ## methods to access per-object data ##
  152. ## ##
  153. ## With args, they set the value. Without ##
  154. ## any, they only retrieve it/them. ##
  155. ##############################################
  156. sub name {
  157. my $self = shift;
  158. if (@_) { $self->{NAME} = shift }
  159. return $self->{NAME};
  160. }
  161. sub age {
  162. my $self = shift;
  163. if (@_) { $self->{AGE} = shift }
  164. return $self->{AGE};
  165. }
  166. sub peers {
  167. my $self = shift;
  168. if (@_) { @{ $self->{PEERS} } = @_ }
  169. return @{ $self->{PEERS} };
  170. }
  171. 1; # so the require or use succeeds
  172. We've created three methods to access an object's data, name(), age(),
  173. and peers(). These are all substantially similar. If called with an
  174. argument, they set the appropriate field; otherwise they return the
  175. value held by that field, meaning the value of that hash key.
  176. =head2 Planning for the Future: Better Constructors
  177. Even though at this point you may not even know what it means, someday
  178. you're going to worry about inheritance. (You can safely ignore this
  179. for now and worry about it later if you'd like.) To ensure that this
  180. all works out smoothly, you must use the double-argument form of bless().
  181. The second argument is the class into which the referent will be blessed.
  182. By not assuming our own class as the default second argument and instead
  183. using the class passed into us, we make our constructor inheritable.
  184. While we're at it, let's make our constructor a bit more flexible.
  185. Rather than being uniquely a class method, we'll set it up so that
  186. it can be called as either a class method I<or> an object
  187. method. That way you can say:
  188. $me = Person->new();
  189. $him = $me->new();
  190. To do this, all we have to do is check whether what was passed in
  191. was a reference or not. If so, we were invoked as an object method,
  192. and we need to extract the package (class) using the ref() function.
  193. If not, we just use the string passed in as the package name
  194. for blessing our referent.
  195. sub new {
  196. my $proto = shift;
  197. my $class = ref($proto) || $proto;
  198. my $self = {};
  199. $self->{NAME} = undef;
  200. $self->{AGE} = undef;
  201. $self->{PEERS} = [];
  202. bless ($self, $class);
  203. return $self;
  204. }
  205. That's about all there is for constructors. These methods bring objects
  206. to life, returning neat little opaque bundles to the user to be used in
  207. subsequent method calls.
  208. =head2 Destructors
  209. Every story has a beginning and an end. The beginning of the object's
  210. story is its constructor, explicitly called when the object comes into
  211. existence. But the ending of its story is the I<destructor>, a method
  212. implicitly called when an object leaves this life. Any per-object
  213. clean-up code is placed in the destructor, which must (in Perl) be called
  214. DESTROY.
  215. If constructors can have arbitrary names, then why not destructors?
  216. Because while a constructor is explicitly called, a destructor is not.
  217. Destruction happens automatically via Perl's garbage collection (GC)
  218. system, which is a quick but somewhat lazy reference-based GC system.
  219. To know what to call, Perl insists that the destructor be named DESTROY.
  220. Perl's notion of the right time to call a destructor is not well-defined
  221. currently, which is why your destructors should not rely on when they are
  222. called.
  223. Why is DESTROY in all caps? Perl on occasion uses purely uppercase
  224. function names as a convention to indicate that the function will
  225. be automatically called by Perl in some way. Others that are called
  226. implicitly include BEGIN, END, AUTOLOAD, plus all methods used by
  227. tied objects, described in L<perltie>.
  228. In really good object-oriented programming languages, the user doesn't
  229. care when the destructor is called. It just happens when it's supposed
  230. to. In low-level languages without any GC at all, there's no way to
  231. depend on this happening at the right time, so the programmer must
  232. explicitly call the destructor to clean up memory and state, crossing
  233. their fingers that it's the right time to do so. Unlike C++, an
  234. object destructor is nearly never needed in Perl, and even when it is,
  235. explicit invocation is uncalled for. In the case of our Person class,
  236. we don't need a destructor because Perl takes care of simple matters
  237. like memory deallocation.
  238. The only situation where Perl's reference-based GC won't work is
  239. when there's a circularity in the data structure, such as:
  240. $this->{WHATEVER} = $this;
  241. In that case, you must delete the self-reference manually if you expect
  242. your program not to leak memory. While admittedly error-prone, this is
  243. the best we can do right now. Nonetheless, rest assured that when your
  244. program is finished, its objects' destructors are all duly called.
  245. So you are guaranteed that an object I<eventually> gets properly
  246. destroyed, except in the unique case of a program that never exits.
  247. (If you're running Perl embedded in another application, this full GC
  248. pass happens a bit more frequently--whenever a thread shuts down.)
  249. =head2 Other Object Methods
  250. The methods we've talked about so far have either been constructors or
  251. else simple "data methods", interfaces to data stored in the object.
  252. These are a bit like an object's data members in the C++ world, except
  253. that strangers don't access them as data. Instead, they should only
  254. access the object's data indirectly via its methods. This is an
  255. important rule: in Perl, access to an object's data should I<only>
  256. be made through methods.
  257. Perl doesn't impose restrictions on who gets to use which methods.
  258. The public-versus-private distinction is by convention, not syntax.
  259. (Well, unless you use the Alias module described below in
  260. L<Data Members as Variables>.) Occasionally you'll see method names beginning or ending
  261. with an underscore or two. This marking is a convention indicating
  262. that the methods are private to that class alone and sometimes to its
  263. closest acquaintances, its immediate subclasses. But this distinction
  264. is not enforced by Perl itself. It's up to the programmer to behave.
  265. There's no reason to limit methods to those that simply access data.
  266. Methods can do anything at all. The key point is that they're invoked
  267. against an object or a class. Let's say we'd like object methods that
  268. do more than fetch or set one particular field.
  269. sub exclaim {
  270. my $self = shift;
  271. return sprintf "Hi, I'm %s, age %d, working with %s",
  272. $self->{NAME}, $self->{AGE}, join(", ", @{$self->{PEERS}});
  273. }
  274. Or maybe even one like this:
  275. sub happy_birthday {
  276. my $self = shift;
  277. return ++$self->{AGE};
  278. }
  279. Some might argue that one should go at these this way:
  280. sub exclaim {
  281. my $self = shift;
  282. return sprintf "Hi, I'm %s, age %d, working with %s",
  283. $self->name, $self->age, join(", ", $self->peers);
  284. }
  285. sub happy_birthday {
  286. my $self = shift;
  287. return $self->age( $self->age() + 1 );
  288. }
  289. But since these methods are all executing in the class itself, this
  290. may not be critical. There are tradeoffs to be made. Using direct
  291. hash access is faster (about an order of magnitude faster, in fact), and
  292. it's more convenient when you want to interpolate in strings. But using
  293. methods (the external interface) internally shields not just the users of
  294. your class but even you yourself from changes in your data representation.
  295. =head1 Class Data
  296. What about "class data", data items common to each object in a class?
  297. What would you want that for? Well, in your Person class, you might
  298. like to keep track of the total people alive. How do you implement that?
  299. You I<could> make it a global variable called $Person::Census. But about
  300. only reason you'd do that would be if you I<wanted> people to be able to
  301. get at your class data directly. They could just say $Person::Census
  302. and play around with it. Maybe this is ok in your design scheme.
  303. You might even conceivably want to make it an exported variable. To be
  304. exportable, a variable must be a (package) global. If this were a
  305. traditional module rather than an object-oriented one, you might do that.
  306. While this approach is expected in most traditional modules, it's
  307. generally considered rather poor form in most object modules. In an
  308. object module, you should set up a protective veil to separate interface
  309. from implementation. So provide a class method to access class data
  310. just as you provide object methods to access object data.
  311. So, you I<could> still keep $Census as a package global and rely upon
  312. others to honor the contract of the module and therefore not play around
  313. with its implementation. You could even be supertricky and make $Census a
  314. tied object as described in L<perltie>, thereby intercepting all accesses.
  315. But more often than not, you just want to make your class data a
  316. file-scoped lexical. To do so, simply put this at the top of the file:
  317. my $Census = 0;
  318. Even though the scope of a my() normally expires when the block in which
  319. it was declared is done (in this case the whole file being required or
  320. used), Perl's deep binding of lexical variables guarantees that the
  321. variable will not be deallocated, remaining accessible to functions
  322. declared within that scope. This doesn't work with global variables
  323. given temporary values via local(), though.
  324. Irrespective of whether you leave $Census a package global or make
  325. it instead a file-scoped lexical, you should make these
  326. changes to your Person::new() constructor:
  327. sub new {
  328. my $proto = shift;
  329. my $class = ref($proto) || $proto;
  330. my $self = {};
  331. $Census++;
  332. $self->{NAME} = undef;
  333. $self->{AGE} = undef;
  334. $self->{PEERS} = [];
  335. bless ($self, $class);
  336. return $self;
  337. }
  338. sub population {
  339. return $Census;
  340. }
  341. Now that we've done this, we certainly do need a destructor so that
  342. when Person is destroyed, the $Census goes down. Here's how
  343. this could be done:
  344. sub DESTROY { --$Census }
  345. Notice how there's no memory to deallocate in the destructor? That's
  346. something that Perl takes care of for you all by itself.
  347. Alternatively, you could use the Class::Data::Inheritable module from
  348. CPAN.
  349. =head2 Accessing Class Data
  350. It turns out that this is not really a good way to go about handling
  351. class data. A good scalable rule is that I<you must never reference class
  352. data directly from an object method>. Otherwise you aren't building a
  353. scalable, inheritable class. The object must be the rendezvous point
  354. for all operations, especially from an object method. The globals
  355. (class data) would in some sense be in the "wrong" package in your
  356. derived classes. In Perl, methods execute in the context of the class
  357. they were defined in, I<not> that of the object that triggered them.
  358. Therefore, namespace visibility of package globals in methods is unrelated
  359. to inheritance.
  360. Got that? Maybe not. Ok, let's say that some other class "borrowed"
  361. (well, inherited) the DESTROY method as it was defined above. When those
  362. objects are destroyed, the original $Census variable will be altered,
  363. not the one in the new class's package namespace. Perhaps this is what
  364. you want, but probably it isn't.
  365. Here's how to fix this. We'll store a reference to the data in the
  366. value accessed by the hash key "_CENSUS". Why the underscore? Well,
  367. mostly because an initial underscore already conveys strong feelings
  368. of magicalness to a C programmer. It's really just a mnemonic device
  369. to remind ourselves that this field is special and not to be used as
  370. a public data member in the same way that NAME, AGE, and PEERS are.
  371. (Because we've been developing this code under the strict pragma, prior
  372. to perl version 5.004 we'll have to quote the field name.)
  373. sub new {
  374. my $proto = shift;
  375. my $class = ref($proto) || $proto;
  376. my $self = {};
  377. $self->{NAME} = undef;
  378. $self->{AGE} = undef;
  379. $self->{PEERS} = [];
  380. # "private" data
  381. $self->{"_CENSUS"} = \$Census;
  382. bless ($self, $class);
  383. ++ ${ $self->{"_CENSUS"} };
  384. return $self;
  385. }
  386. sub population {
  387. my $self = shift;
  388. if (ref $self) {
  389. return ${ $self->{"_CENSUS"} };
  390. } else {
  391. return $Census;
  392. }
  393. }
  394. sub DESTROY {
  395. my $self = shift;
  396. -- ${ $self->{"_CENSUS"} };
  397. }
  398. =head2 Debugging Methods
  399. It's common for a class to have a debugging mechanism. For example,
  400. you might want to see when objects are created or destroyed. To do that,
  401. add a debugging variable as a file-scoped lexical. For this, we'll pull
  402. in the standard Carp module to emit our warnings and fatal messages.
  403. That way messages will come out with the caller's filename and
  404. line number instead of our own; if we wanted them to be from our own
  405. perspective, we'd just use die() and warn() directly instead of croak()
  406. and carp() respectively.
  407. use Carp;
  408. my $Debugging = 0;
  409. Now add a new class method to access the variable.
  410. sub debug {
  411. my $class = shift;
  412. if (ref $class) { confess "Class method called as object method" }
  413. unless (@_ == 1) { confess "usage: CLASSNAME->debug(level)" }
  414. $Debugging = shift;
  415. }
  416. Now fix up DESTROY to murmur a bit as the moribund object expires:
  417. sub DESTROY {
  418. my $self = shift;
  419. if ($Debugging) { carp "Destroying $self " . $self->name }
  420. -- ${ $self->{"_CENSUS"} };
  421. }
  422. One could conceivably make a per-object debug state. That
  423. way you could call both of these:
  424. Person->debug(1); # entire class
  425. $him->debug(1); # just this object
  426. To do so, we need our debugging method to be a "bimodal" one, one that
  427. works on both classes I<and> objects. Therefore, adjust the debug()
  428. and DESTROY methods as follows:
  429. sub debug {
  430. my $self = shift;
  431. confess "usage: thing->debug(level)" unless @_ == 1;
  432. my $level = shift;
  433. if (ref($self)) {
  434. $self->{"_DEBUG"} = $level; # just myself
  435. } else {
  436. $Debugging = $level; # whole class
  437. }
  438. }
  439. sub DESTROY {
  440. my $self = shift;
  441. if ($Debugging || $self->{"_DEBUG"}) {
  442. carp "Destroying $self " . $self->name;
  443. }
  444. -- ${ $self->{"_CENSUS"} };
  445. }
  446. What happens if a derived class (which we'll call Employee) inherits
  447. methods from this Person base class? Then C<< Employee->debug() >>, when called
  448. as a class method, manipulates $Person::Debugging not $Employee::Debugging.
  449. =head2 Class Destructors
  450. The object destructor handles the death of each distinct object. But sometimes
  451. you want a bit of cleanup when the entire class is shut down, which
  452. currently only happens when the program exits. To make such a
  453. I<class destructor>, create a function in that class's package named
  454. END. This works just like the END function in traditional modules,
  455. meaning that it gets called whenever your program exits unless it execs
  456. or dies of an uncaught signal. For example,
  457. sub END {
  458. if ($Debugging) {
  459. print "All persons are going away now.\n";
  460. }
  461. }
  462. When the program exits, all the class destructors (END functions) are
  463. be called in the opposite order that they were loaded in (LIFO order).
  464. =head2 Documenting the Interface
  465. And there you have it: we've just shown you the I<implementation> of this
  466. Person class. Its I<interface> would be its documentation. Usually this
  467. means putting it in pod ("plain old documentation") format right there
  468. in the same file. In our Person example, we would place the following
  469. docs anywhere in the Person.pm file. Even though it looks mostly like
  470. code, it's not. It's embedded documentation such as would be used by
  471. the pod2man, pod2html, or pod2text programs. The Perl compiler ignores
  472. pods entirely, just as the translators ignore code. Here's an example of
  473. some pods describing the informal interface:
  474. =head1 NAME
  475. Person - class to implement people
  476. =head1 SYNOPSIS
  477. use Person;
  478. #################
  479. # class methods #
  480. #################
  481. $ob = Person->new;
  482. $count = Person->population;
  483. #######################
  484. # object data methods #
  485. #######################
  486. ### get versions ###
  487. $who = $ob->name;
  488. $years = $ob->age;
  489. @pals = $ob->peers;
  490. ### set versions ###
  491. $ob->name("Jason");
  492. $ob->age(23);
  493. $ob->peers( "Norbert", "Rhys", "Phineas" );
  494. ########################
  495. # other object methods #
  496. ########################
  497. $phrase = $ob->exclaim;
  498. $ob->happy_birthday;
  499. =head1 DESCRIPTION
  500. The Person class implements dah dee dah dee dah....
  501. That's all there is to the matter of interface versus implementation.
  502. A programmer who opens up the module and plays around with all the private
  503. little shiny bits that were safely locked up behind the interface contract
  504. has voided the warranty, and you shouldn't worry about their fate.
  505. =head1 Aggregation
  506. Suppose you later want to change the class to implement better names.
  507. Perhaps you'd like to support both given names (called Christian names,
  508. irrespective of one's religion) and family names (called surnames), plus
  509. nicknames and titles. If users of your Person class have been properly
  510. accessing it through its documented interface, then you can easily change
  511. the underlying implementation. If they haven't, then they lose and
  512. it's their fault for breaking the contract and voiding their warranty.
  513. To do this, we'll make another class, this one called Fullname. What's
  514. the Fullname class look like? To answer that question, you have to
  515. first figure out how you want to use it. How about we use it this way:
  516. $him = Person->new();
  517. $him->fullname->title("St");
  518. $him->fullname->christian("Thomas");
  519. $him->fullname->surname("Aquinas");
  520. $him->fullname->nickname("Tommy");
  521. printf "His normal name is %s\n", $him->name;
  522. printf "But his real name is %s\n", $him->fullname->as_string;
  523. Ok. To do this, we'll change Person::new() so that it supports
  524. a full name field this way:
  525. sub new {
  526. my $proto = shift;
  527. my $class = ref($proto) || $proto;
  528. my $self = {};
  529. $self->{FULLNAME} = Fullname->new();
  530. $self->{AGE} = undef;
  531. $self->{PEERS} = [];
  532. $self->{"_CENSUS"} = \$Census;
  533. bless ($self, $class);
  534. ++ ${ $self->{"_CENSUS"} };
  535. return $self;
  536. }
  537. sub fullname {
  538. my $self = shift;
  539. return $self->{FULLNAME};
  540. }
  541. Then to support old code, define Person::name() this way:
  542. sub name {
  543. my $self = shift;
  544. return $self->{FULLNAME}->nickname(@_)
  545. || $self->{FULLNAME}->christian(@_);
  546. }
  547. Here's the Fullname class. We'll use the same technique
  548. of using a hash reference to hold data fields, and methods
  549. by the appropriate name to access them:
  550. package Fullname;
  551. use strict;
  552. sub new {
  553. my $proto = shift;
  554. my $class = ref($proto) || $proto;
  555. my $self = {
  556. TITLE => undef,
  557. CHRISTIAN => undef,
  558. SURNAME => undef,
  559. NICK => undef,
  560. };
  561. bless ($self, $class);
  562. return $self;
  563. }
  564. sub christian {
  565. my $self = shift;
  566. if (@_) { $self->{CHRISTIAN} = shift }
  567. return $self->{CHRISTIAN};
  568. }
  569. sub surname {
  570. my $self = shift;
  571. if (@_) { $self->{SURNAME} = shift }
  572. return $self->{SURNAME};
  573. }
  574. sub nickname {
  575. my $self = shift;
  576. if (@_) { $self->{NICK} = shift }
  577. return $self->{NICK};
  578. }
  579. sub title {
  580. my $self = shift;
  581. if (@_) { $self->{TITLE} = shift }
  582. return $self->{TITLE};
  583. }
  584. sub as_string {
  585. my $self = shift;
  586. my $name = join(" ", @$self{'CHRISTIAN', 'SURNAME'});
  587. if ($self->{TITLE}) {
  588. $name = $self->{TITLE} . " " . $name;
  589. }
  590. return $name;
  591. }
  592. 1;
  593. Finally, here's the test program:
  594. #!/usr/bin/perl -w
  595. use strict;
  596. use Person;
  597. sub END { show_census() }
  598. sub show_census () {
  599. printf "Current population: %d\n", Person->population;
  600. }
  601. Person->debug(1);
  602. show_census();
  603. my $him = Person->new();
  604. $him->fullname->christian("Thomas");
  605. $him->fullname->surname("Aquinas");
  606. $him->fullname->nickname("Tommy");
  607. $him->fullname->title("St");
  608. $him->age(1);
  609. printf "%s is really %s.\n", $him->name, $him->fullname;
  610. printf "%s's age: %d.\n", $him->name, $him->age;
  611. $him->happy_birthday;
  612. printf "%s's age: %d.\n", $him->name, $him->age;
  613. show_census();
  614. =head1 Inheritance
  615. Object-oriented programming systems all support some notion of
  616. inheritance. Inheritance means allowing one class to piggy-back on
  617. top of another one so you don't have to write the same code again and
  618. again. It's about software reuse, and therefore related to Laziness,
  619. the principal virtue of a programmer. (The import/export mechanisms in
  620. traditional modules are also a form of code reuse, but a simpler one than
  621. the true inheritance that you find in object modules.)
  622. Sometimes the syntax of inheritance is built into the core of the
  623. language, and sometimes it's not. Perl has no special syntax for
  624. specifying the class (or classes) to inherit from. Instead, it's all
  625. strictly in the semantics. Each package can have a variable called @ISA,
  626. which governs (method) inheritance. If you try to call a method on an
  627. object or class, and that method is not found in that object's package,
  628. Perl then looks to @ISA for other packages to go looking through in
  629. search of the missing method.
  630. Like the special per-package variables recognized by Exporter (such as
  631. @EXPORT, @EXPORT_OK, @EXPORT_FAIL, %EXPORT_TAGS, and $VERSION), the @ISA
  632. array I<must> be a package-scoped global and not a file-scoped lexical
  633. created via my(). Most classes have just one item in their @ISA array.
  634. In this case, we have what's called "single inheritance", or SI for short.
  635. Consider this class:
  636. package Employee;
  637. use Person;
  638. @ISA = ("Person");
  639. 1;
  640. Not a lot to it, eh? All it's doing so far is loading in another
  641. class and stating that this one will inherit methods from that
  642. other class if need be. We have given it none of its own methods.
  643. We rely upon an Employee to behave just like a Person.
  644. Setting up an empty class like this is called the "empty subclass test";
  645. that is, making a derived class that does nothing but inherit from a
  646. base class. If the original base class has been designed properly,
  647. then the new derived class can be used as a drop-in replacement for the
  648. old one. This means you should be able to write a program like this:
  649. use Employee;
  650. my $empl = Employee->new();
  651. $empl->name("Jason");
  652. $empl->age(23);
  653. printf "%s is age %d.\n", $empl->name, $empl->age;
  654. By proper design, we mean always using the two-argument form of bless(),
  655. avoiding direct access of global data, and not exporting anything. If you
  656. look back at the Person::new() function we defined above, we were careful
  657. to do that. There's a bit of package data used in the constructor,
  658. but the reference to this is stored on the object itself and all other
  659. methods access package data via that reference, so we should be ok.
  660. What do we mean by the Person::new() function -- isn't that actually
  661. a method? Well, in principle, yes. A method is just a function that
  662. expects as its first argument a class name (package) or object
  663. (blessed reference). Person::new() is the function that both the
  664. C<< Person->new() >> method and the C<< Employee->new() >> method end
  665. up calling. Understand that while a method call looks a lot like a
  666. function call, they aren't really quite the same, and if you treat them
  667. as the same, you'll very soon be left with nothing but broken programs.
  668. First, the actual underlying calling conventions are different: method
  669. calls get an extra argument. Second, function calls don't do inheritance,
  670. but methods do.
  671. Method Call Resulting Function Call
  672. ----------- ------------------------
  673. Person->new() Person::new("Person")
  674. Employee->new() Person::new("Employee")
  675. So don't use function calls when you mean to call a method.
  676. If an employee is just a Person, that's not all too very interesting.
  677. So let's add some other methods. We'll give our employee
  678. data fields to access their salary, their employee ID, and their
  679. start date.
  680. If you're getting a little tired of creating all these nearly identical
  681. methods just to get at the object's data, do not despair. Later,
  682. we'll describe several different convenience mechanisms for shortening
  683. this up. Meanwhile, here's the straight-forward way:
  684. sub salary {
  685. my $self = shift;
  686. if (@_) { $self->{SALARY} = shift }
  687. return $self->{SALARY};
  688. }
  689. sub id_number {
  690. my $self = shift;
  691. if (@_) { $self->{ID} = shift }
  692. return $self->{ID};
  693. }
  694. sub start_date {
  695. my $self = shift;
  696. if (@_) { $self->{START_DATE} = shift }
  697. return $self->{START_DATE};
  698. }
  699. =head2 Overridden Methods
  700. What happens when both a derived class and its base class have the same
  701. method defined? Well, then you get the derived class's version of that
  702. method. For example, let's say that we want the peers() method called on
  703. an employee to act a bit differently. Instead of just returning the list
  704. of peer names, let's return slightly different strings. So doing this:
  705. $empl->peers("Peter", "Paul", "Mary");
  706. printf "His peers are: %s\n", join(", ", $empl->peers);
  707. will produce:
  708. His peers are: PEON=PETER, PEON=PAUL, PEON=MARY
  709. To do this, merely add this definition into the Employee.pm file:
  710. sub peers {
  711. my $self = shift;
  712. if (@_) { @{ $self->{PEERS} } = @_ }
  713. return map { "PEON=\U$_" } @{ $self->{PEERS} };
  714. }
  715. There, we've just demonstrated the high-falutin' concept known in certain
  716. circles as I<polymorphism>. We've taken on the form and behaviour of
  717. an existing object, and then we've altered it to suit our own purposes.
  718. This is a form of Laziness. (Getting polymorphed is also what happens
  719. when the wizard decides you'd look better as a frog.)
  720. Every now and then you'll want to have a method call trigger both its
  721. derived class (also known as "subclass") version as well as its base class
  722. (also known as "superclass") version. In practice, constructors and
  723. destructors are likely to want to do this, and it probably also makes
  724. sense in the debug() method we showed previously.
  725. To do this, add this to Employee.pm:
  726. use Carp;
  727. my $Debugging = 0;
  728. sub debug {
  729. my $self = shift;
  730. confess "usage: thing->debug(level)" unless @_ == 1;
  731. my $level = shift;
  732. if (ref($self)) {
  733. $self->{"_DEBUG"} = $level;
  734. } else {
  735. $Debugging = $level; # whole class
  736. }
  737. Person::debug($self, $Debugging); # don't really do this
  738. }
  739. As you see, we turn around and call the Person package's debug() function.
  740. But this is far too fragile for good design. What if Person doesn't
  741. have a debug() function, but is inheriting I<its> debug() method
  742. from elsewhere? It would have been slightly better to say
  743. Person->debug($Debugging);
  744. But even that's got too much hard-coded. It's somewhat better to say
  745. $self->Person::debug($Debugging);
  746. Which is a funny way to say to start looking for a debug() method up
  747. in Person. This strategy is more often seen on overridden object methods
  748. than on overridden class methods.
  749. There is still something a bit off here. We've hard-coded our
  750. superclass's name. This in particular is bad if you change which classes
  751. you inherit from, or add others. Fortunately, the pseudoclass SUPER
  752. comes to the rescue here.
  753. $self->SUPER::debug($Debugging);
  754. This way it starts looking in my class's @ISA. This only makes sense
  755. from I<within> a method call, though. Don't try to access anything
  756. in SUPER:: from anywhere else, because it doesn't exist outside
  757. an overridden method call.
  758. Things are getting a bit complicated here. Have we done anything
  759. we shouldn't? As before, one way to test whether we're designing
  760. a decent class is via the empty subclass test. Since we already have
  761. an Employee class that we're trying to check, we'd better get a new
  762. empty subclass that can derive from Employee. Here's one:
  763. package Boss;
  764. use Employee; # :-)
  765. @ISA = qw(Employee);
  766. And here's the test program:
  767. #!/usr/bin/perl -w
  768. use strict;
  769. use Boss;
  770. Boss->debug(1);
  771. my $boss = Boss->new();
  772. $boss->fullname->title("Don");
  773. $boss->fullname->surname("Pichon Alvarez");
  774. $boss->fullname->christian("Federico Jesus");
  775. $boss->fullname->nickname("Fred");
  776. $boss->age(47);
  777. $boss->peers("Frank", "Felipe", "Faust");
  778. printf "%s is age %d.\n", $boss->fullname, $boss->age;
  779. printf "His peers are: %s\n", join(", ", $boss->peers);
  780. Running it, we see that we're still ok. If you'd like to dump out your
  781. object in a nice format, somewhat like the way the 'x' command works in
  782. the debugger, you could use the Data::Dumper module from CPAN this way:
  783. use Data::Dumper;
  784. print "Here's the boss:\n";
  785. print Dumper($boss);
  786. Which shows us something like this:
  787. Here's the boss:
  788. $VAR1 = bless( {
  789. _CENSUS => \1,
  790. FULLNAME => bless( {
  791. TITLE => 'Don',
  792. SURNAME => 'Pichon Alvarez',
  793. NICK => 'Fred',
  794. CHRISTIAN => 'Federico Jesus'
  795. }, 'Fullname' ),
  796. AGE => 47,
  797. PEERS => [
  798. 'Frank',
  799. 'Felipe',
  800. 'Faust'
  801. ]
  802. }, 'Boss' );
  803. Hm.... something's missing there. What about the salary, start date,
  804. and ID fields? Well, we never set them to anything, even undef, so they
  805. don't show up in the hash's keys. The Employee class has no new() method
  806. of its own, and the new() method in Person doesn't know about Employees.
  807. (Nor should it: proper OO design dictates that a subclass be allowed to
  808. know about its immediate superclass, but never vice-versa.) So let's
  809. fix up Employee::new() this way:
  810. sub new {
  811. my $proto = shift;
  812. my $class = ref($proto) || $proto;
  813. my $self = $class->SUPER::new();
  814. $self->{SALARY} = undef;
  815. $self->{ID} = undef;
  816. $self->{START_DATE} = undef;
  817. bless ($self, $class); # reconsecrate
  818. return $self;
  819. }
  820. Now if you dump out an Employee or Boss object, you'll find
  821. that new fields show up there now.
  822. =head2 Multiple Inheritance
  823. Ok, at the risk of confusing beginners and annoying OO gurus, it's
  824. time to confess that Perl's object system includes that controversial
  825. notion known as multiple inheritance, or MI for short. All this means
  826. is that rather than having just one parent class who in turn might
  827. itself have a parent class, etc., that you can directly inherit from
  828. two or more parents. It's true that some uses of MI can get you into
  829. trouble, although hopefully not quite so much trouble with Perl as with
  830. dubiously-OO languages like C++.
  831. The way it works is actually pretty simple: just put more than one package
  832. name in your @ISA array. When it comes time for Perl to go finding
  833. methods for your object, it looks at each of these packages in order.
  834. Well, kinda. It's actually a fully recursive, depth-first order.
  835. Consider a bunch of @ISA arrays like this:
  836. @First::ISA = qw( Alpha );
  837. @Second::ISA = qw( Beta );
  838. @Third::ISA = qw( First Second );
  839. If you have an object of class Third:
  840. my $ob = Third->new();
  841. $ob->spin();
  842. How do we find a spin() method (or a new() method for that matter)?
  843. Because the search is depth-first, classes will be looked up
  844. in the following order: Third, First, Alpha, Second, and Beta.
  845. In practice, few class modules have been seen that actually
  846. make use of MI. One nearly always chooses simple containership of
  847. one class within another over MI. That's why our Person
  848. object I<contained> a Fullname object. That doesn't mean
  849. it I<was> one.
  850. However, there is one particular area where MI in Perl is rampant:
  851. borrowing another class's class methods. This is rather common,
  852. especially with some bundled "objectless" classes,
  853. like Exporter, DynaLoader, AutoLoader, and SelfLoader. These classes
  854. do not provide constructors; they exist only so you may inherit their
  855. class methods. (It's not entirely clear why inheritance was done
  856. here rather than traditional module importation.)
  857. For example, here is the POSIX module's @ISA:
  858. package POSIX;
  859. @ISA = qw(Exporter DynaLoader);
  860. The POSIX module isn't really an object module, but then,
  861. neither are Exporter or DynaLoader. They're just lending their
  862. classes' behaviours to POSIX.
  863. Why don't people use MI for object methods much? One reason is that
  864. it can have complicated side-effects. For one thing, your inheritance
  865. graph (no longer a tree) might converge back to the same base class.
  866. Although Perl guards against recursive inheritance, merely having parents
  867. who are related to each other via a common ancestor, incestuous though
  868. it sounds, is not forbidden. What if in our Third class shown above we
  869. wanted its new() method to also call both overridden constructors in its
  870. two parent classes? The SUPER notation would only find the first one.
  871. Also, what about if the Alpha and Beta classes both had a common ancestor,
  872. like Nought? If you kept climbing up the inheritance tree calling
  873. overridden methods, you'd end up calling Nought::new() twice,
  874. which might well be a bad idea.
  875. =head2 UNIVERSAL: The Root of All Objects
  876. Wouldn't it be convenient if all objects were rooted at some ultimate
  877. base class? That way you could give every object common methods without
  878. having to go and add it to each and every @ISA. Well, it turns out that
  879. you can. You don't see it, but Perl tacitly and irrevocably assumes
  880. that there's an extra element at the end of @ISA: the class UNIVERSAL.
  881. In version 5.003, there were no predefined methods there, but you could put
  882. whatever you felt like into it.
  883. However, as of version 5.004 (or some subversive releases, like 5.003_08),
  884. UNIVERSAL has some methods in it already. These are builtin to your Perl
  885. binary, so they don't take any extra time to load. Predefined methods
  886. include isa(), can(), and VERSION(). isa() tells you whether an object or
  887. class "is" another one without having to traverse the hierarchy yourself:
  888. $has_io = $fd->isa("IO::Handle");
  889. $itza_handle = IO::Socket->isa("IO::Handle");
  890. The can() method, called against that object or class, reports back
  891. whether its string argument is a callable method name in that class.
  892. In fact, it gives you back a function reference to that method:
  893. $his_print_method = $obj->can('as_string');
  894. Finally, the VERSION method checks whether the class (or the object's
  895. class) has a package global called $VERSION that's high enough, as in:
  896. Some_Module->VERSION(3.0);
  897. $his_vers = $ob->VERSION();
  898. However, we don't usually call VERSION ourselves. (Remember that an all
  899. uppercase function name is a Perl convention that indicates that the
  900. function will be automatically used by Perl in some way.) In this case,
  901. it happens when you say
  902. use Some_Module 3.0;
  903. If you wanted to add version checking to your Person class explained
  904. above, just add this to Person.pm:
  905. our $VERSION = '1.1';
  906. and then in Employee.pm could you can say
  907. use Employee 1.1;
  908. And it would make sure that you have at least that version number or
  909. higher available. This is not the same as loading in that exact version
  910. number. No mechanism currently exists for concurrent installation of
  911. multiple versions of a module. Lamentably.
  912. =head1 Alternate Object Representations
  913. Nothing requires objects to be implemented as hash references. An object
  914. can be any sort of reference so long as its referent has been suitably
  915. blessed. That means scalar, array, and code references are also fair
  916. game.
  917. A scalar would work if the object has only one datum to hold. An array
  918. would work for most cases, but makes inheritance a bit dodgy because
  919. you have to invent new indices for the derived classes.
  920. =head2 Arrays as Objects
  921. If the user of your class honors the contract and sticks to the advertised
  922. interface, then you can change its underlying interface if you feel
  923. like it. Here's another implementation that conforms to the same
  924. interface specification. This time we'll use an array reference
  925. instead of a hash reference to represent the object.
  926. package Person;
  927. use strict;
  928. my($NAME, $AGE, $PEERS) = ( 0 .. 2 );
  929. ############################################
  930. ## the object constructor (array version) ##
  931. ############################################
  932. sub new {
  933. my $self = [];
  934. $self->[$NAME] = undef; # this is unnecessary
  935. $self->[$AGE] = undef; # as is this
  936. $self->[$PEERS] = []; # but this isn't, really
  937. bless($self);
  938. return $self;
  939. }
  940. sub name {
  941. my $self = shift;
  942. if (@_) { $self->[$NAME] = shift }
  943. return $self->[$NAME];
  944. }
  945. sub age {
  946. my $self = shift;
  947. if (@_) { $self->[$AGE] = shift }
  948. return $self->[$AGE];
  949. }
  950. sub peers {
  951. my $self = shift;
  952. if (@_) { @{ $self->[$PEERS] } = @_ }
  953. return @{ $self->[$PEERS] };
  954. }
  955. 1; # so the require or use succeeds
  956. You might guess that the array access would be a lot faster than the
  957. hash access, but they're actually comparable. The array is a I<little>
  958. bit faster, but not more than ten or fifteen percent, even when you
  959. replace the variables above like $AGE with literal numbers, like 1.
  960. A bigger difference between the two approaches can be found in memory use.
  961. A hash representation takes up more memory than an array representation
  962. because you have to allocate memory for the keys as well as for the values.
  963. However, it really isn't that bad, especially since as of version 5.004,
  964. memory is only allocated once for a given hash key, no matter how many
  965. hashes have that key. It's expected that sometime in the future, even
  966. these differences will fade into obscurity as more efficient underlying
  967. representations are devised.
  968. Still, the tiny edge in speed (and somewhat larger one in memory)
  969. is enough to make some programmers choose an array representation
  970. for simple classes. There's still a little problem with
  971. scalability, though, because later in life when you feel
  972. like creating subclasses, you'll find that hashes just work
  973. out better.
  974. =head2 Closures as Objects
  975. Using a code reference to represent an object offers some fascinating
  976. possibilities. We can create a new anonymous function (closure) who
  977. alone in all the world can see the object's data. This is because we
  978. put the data into an anonymous hash that's lexically visible only to
  979. the closure we create, bless, and return as the object. This object's
  980. methods turn around and call the closure as a regular subroutine call,
  981. passing it the field we want to affect. (Yes,
  982. the double-function call is slow, but if you wanted fast, you wouldn't
  983. be using objects at all, eh? :-)
  984. Use would be similar to before:
  985. use Person;
  986. $him = Person->new();
  987. $him->name("Jason");
  988. $him->age(23);
  989. $him->peers( [ "Norbert", "Rhys", "Phineas" ] );
  990. printf "%s is %d years old.\n", $him->name, $him->age;
  991. print "His peers are: ", join(", ", @{$him->peers}), "\n";
  992. but the implementation would be radically, perhaps even sublimely
  993. different:
  994. package Person;
  995. sub new {
  996. my $that = shift;
  997. my $class = ref($that) || $that;
  998. my $self = {
  999. NAME => undef,
  1000. AGE => undef,
  1001. PEERS => [],
  1002. };
  1003. my $closure = sub {
  1004. my $field = shift;
  1005. if (@_) { $self->{$field} = shift }
  1006. return $self->{$field};
  1007. };
  1008. bless($closure, $class);
  1009. return $closure;
  1010. }
  1011. sub name { &{ $_[0] }("NAME", @_[ 1 .. $#_ ] ) }
  1012. sub age { &{ $_[0] }("AGE", @_[ 1 .. $#_ ] ) }
  1013. sub peers { &{ $_[0] }("PEERS", @_[ 1 .. $#_ ] ) }
  1014. 1;
  1015. Because this object is hidden behind a code reference, it's probably a bit
  1016. mysterious to those whose background is more firmly rooted in standard
  1017. procedural or object-based programming languages than in functional
  1018. programming languages whence closures derive. The object
  1019. created and returned by the new() method is itself not a data reference
  1020. as we've seen before. It's an anonymous code reference that has within
  1021. it access to a specific version (lexical binding and instantiation)
  1022. of the object's data, which are stored in the private variable $self.
  1023. Although this is the same function each time, it contains a different
  1024. version of $self.
  1025. When a method like C<$him-E<gt>name("Jason")> is called, its implicit
  1026. zeroth argument is the invoking object--just as it is with all method
  1027. calls. But in this case, it's our code reference (something like a
  1028. function pointer in C++, but with deep binding of lexical variables).
  1029. There's not a lot to be done with a code reference beyond calling it, so
  1030. that's just what we do when we say C<&{$_[0]}>. This is just a regular
  1031. function call, not a method call. The initial argument is the string
  1032. "NAME", and any remaining arguments are whatever had been passed to the
  1033. method itself.
  1034. Once we're executing inside the closure that had been created in new(),
  1035. the $self hash reference suddenly becomes visible. The closure grabs
  1036. its first argument ("NAME" in this case because that's what the name()
  1037. method passed it), and uses that string to subscript into the private
  1038. hash hidden in its unique version of $self.
  1039. Nothing under the sun will allow anyone outside the executing method to
  1040. be able to get at this hidden data. Well, nearly nothing. You I<could>
  1041. single step through the program using the debugger and find out the
  1042. pieces while you're in the method, but everyone else is out of luck.
  1043. There, if that doesn't excite the Scheme folks, then I just don't know
  1044. what will. Translation of this technique into C++, Java, or any other
  1045. braindead-static language is left as a futile exercise for aficionados
  1046. of those camps.
  1047. You could even add a bit of nosiness via the caller() function and
  1048. make the closure refuse to operate unless called via its own package.
  1049. This would no doubt satisfy certain fastidious concerns of programming
  1050. police and related puritans.
  1051. If you were wondering when Hubris, the third principle virtue of a
  1052. programmer, would come into play, here you have it. (More seriously,
  1053. Hubris is just the pride in craftsmanship that comes from having written
  1054. a sound bit of well-designed code.)
  1055. =head1 AUTOLOAD: Proxy Methods
  1056. Autoloading is a way to intercept calls to undefined methods. An autoload
  1057. routine may choose to create a new function on the fly, either loaded
  1058. from disk or perhaps just eval()ed right there. This define-on-the-fly
  1059. strategy is why it's called autoloading.
  1060. But that's only one possible approach. Another one is to just
  1061. have the autoloaded method itself directly provide the
  1062. requested service. When used in this way, you may think
  1063. of autoloaded methods as "proxy" methods.
  1064. When Perl tries to call an undefined function in a particular package
  1065. and that function is not defined, it looks for a function in
  1066. that same package called AUTOLOAD. If one exists, it's called
  1067. with the same arguments as the original function would have had.
  1068. The fully-qualified name of the function is stored in that package's
  1069. global variable $AUTOLOAD. Once called, the function can do anything
  1070. it would like, including defining a new function by the right name, and
  1071. then doing a really fancy kind of C<goto> right to it, erasing itself
  1072. from the call stack.
  1073. What does this have to do with objects? After all, we keep talking about
  1074. functions, not methods. Well, since a method is just a function with
  1075. an extra argument and some fancier semantics about where it's found,
  1076. we can use autoloading for methods, too. Perl doesn't start looking
  1077. for an AUTOLOAD method until it has exhausted the recursive hunt up
  1078. through @ISA, though. Some programmers have even been known to define
  1079. a UNIVERSAL::AUTOLOAD method to trap unresolved method calls to any
  1080. kind of object.
  1081. =head2 Autoloaded Data Methods
  1082. You probably began to get a little suspicious about the duplicated
  1083. code way back earlier when we first showed you the Person class, and
  1084. then later the Employee class. Each method used to access the
  1085. hash fields looked virtually identical. This should have tickled
  1086. that great programming virtue, Impatience, but for the time,
  1087. we let Laziness win out, and so did nothing. Proxy methods can cure
  1088. this.
  1089. Instead of writing a new function every time we want a new data field,
  1090. we'll use the autoload mechanism to generate (actually, mimic) methods on
  1091. the fly. To verify that we're accessing a valid member, we will check
  1092. against an C<_permitted> (pronounced "under-permitted") field, which
  1093. is a reference to a file-scoped lexical (like a C file static) hash of permitted fields in this record
  1094. called %fields. Why the underscore? For the same reason as the _CENSUS
  1095. field we once used: as a marker that means "for internal use only".
  1096. Here's what the module initialization code and class
  1097. constructor will look like when taking this approach:
  1098. package Person;
  1099. use Carp;
  1100. our $AUTOLOAD; # it's a package global
  1101. my %fields = (
  1102. name => undef,
  1103. age => undef,
  1104. peers => undef,
  1105. );
  1106. sub new {
  1107. my $that = shift;
  1108. my $class = ref($that) || $that;
  1109. my $self = {
  1110. _permitted => \%fields,
  1111. %fields,
  1112. };
  1113. bless $self, $class;
  1114. return $self;
  1115. }
  1116. If we wanted our record to have default values, we could fill those in
  1117. where current we have C<undef> in the %fields hash.
  1118. Notice how we saved a reference to our class data on the object itself?
  1119. Remember that it's important to access class data through the object
  1120. itself instead of having any method reference %fields directly, or else
  1121. you won't have a decent inheritance.
  1122. The real magic, though, is going to reside in our proxy method, which
  1123. will handle all calls to undefined methods for objects of class Person
  1124. (or subclasses of Person). It has to be called AUTOLOAD. Again, it's
  1125. all caps because it's called for us implicitly by Perl itself, not by
  1126. a user directly.
  1127. sub AUTOLOAD {
  1128. my $self = shift;
  1129. my $type = ref($self)
  1130. or croak "$self is not an object";
  1131. my $name = $AUTOLOAD;
  1132. $name =~ s/.*://; # strip fully-qualified portion
  1133. unless (exists $self->{_permitted}->{$name} ) {
  1134. croak "Can't access `$name' field in class $type";
  1135. }
  1136. if (@_) {
  1137. return $self->{$name} = shift;
  1138. } else {
  1139. return $self->{$name};
  1140. }
  1141. }
  1142. Pretty nifty, eh? All we have to do to add new data fields
  1143. is modify %fields. No new functions need be written.
  1144. I could have avoided the C<_permitted> field entirely, but I
  1145. wanted to demonstrate how to store a reference to class data on the
  1146. object so you wouldn't have to access that class data
  1147. directly from an object method.
  1148. =head2 Inherited Autoloaded Data Methods
  1149. But what about inheritance? Can we define our Employee
  1150. class similarly? Yes, so long as we're careful enough.
  1151. Here's how to be careful:
  1152. package Employee;
  1153. use Person;
  1154. use strict;
  1155. our @ISA = qw(Person);
  1156. my %fields = (
  1157. id => undef,
  1158. salary => undef,
  1159. );
  1160. sub new {
  1161. my $that = shift;
  1162. my $class = ref($that) || $that;
  1163. my $self = bless $that->SUPER::new(), $class;
  1164. my($element);
  1165. foreach $element (keys %fields) {
  1166. $self->{_permitted}->{$element} = $fields{$element};
  1167. }
  1168. @{$self}{keys %fields} = values %fields;
  1169. return $self;
  1170. }
  1171. Once we've done this, we don't even need to have an
  1172. AUTOLOAD function in the Employee package, because
  1173. we'll grab Person's version of that via inheritance,
  1174. and it will all work out just fine.
  1175. =head1 Metaclassical Tools
  1176. Even though proxy methods can provide a more convenient approach to making
  1177. more struct-like classes than tediously coding up data methods as
  1178. functions, it still leaves a bit to be desired. For one thing, it means
  1179. you have to handle bogus calls that you don't mean to trap via your proxy.
  1180. It also means you have to be quite careful when dealing with inheritance,
  1181. as detailed above.
  1182. Perl programmers have responded to this by creating several different
  1183. class construction classes. These metaclasses are classes
  1184. that create other classes. A couple worth looking at are
  1185. Class::Struct and Alias. These and other related metaclasses can be
  1186. found in the modules directory on CPAN.
  1187. =head2 Class::Struct
  1188. One of the older ones is Class::Struct. In fact, its syntax and
  1189. interface were sketched out long before perl5 even solidified into a
  1190. real thing. What it does is provide you a way to "declare" a class
  1191. as having objects whose fields are of a specific type. The function
  1192. that does this is called, not surprisingly enough, struct(). Because
  1193. structures or records are not base types in Perl, each time you want to
  1194. create a class to provide a record-like data object, you yourself have
  1195. to define a new() method, plus separate data-access methods for each of
  1196. that record's fields. You'll quickly become bored with this process.
  1197. The Class::Struct::struct() function alleviates this tedium.
  1198. Here's a simple example of using it:
  1199. use Class::Struct qw(struct);
  1200. use Jobbie; # user-defined; see below
  1201. struct 'Fred' => {
  1202. one => '$',
  1203. many => '@',
  1204. profession => Jobbie, # calls Jobbie->new()
  1205. };
  1206. $ob = Fred->new;
  1207. $ob->one("hmmmm");
  1208. $ob->many(0, "here");
  1209. $ob->many(1, "you");
  1210. $ob->many(2, "go");
  1211. print "Just set: ", $ob->many(2), "\n";
  1212. $ob->profession->salary(10_000);
  1213. You can declare types in the struct to be basic Perl types, or
  1214. user-defined types (classes). User types will be initialized by calling
  1215. that class's new() method.
  1216. Here's a real-world example of using struct generation. Let's say you
  1217. wanted to override Perl's idea of gethostbyname() and gethostbyaddr() so
  1218. that they would return objects that acted like C structures. We don't
  1219. care about high-falutin' OO gunk. All we want is for these objects to
  1220. act like structs in the C sense.
  1221. use Socket;
  1222. use Net::hostent;
  1223. $h = gethostbyname("perl.com"); # object return
  1224. printf "perl.com's real name is %s, address %s\n",
  1225. $h->name, inet_ntoa($h->addr);
  1226. Here's how to do this using the Class::Struct module.
  1227. The crux is going to be this call:
  1228. struct 'Net::hostent' => [ # note bracket
  1229. name => '$',
  1230. aliases => '@',
  1231. addrtype => '$',
  1232. 'length' => '$',
  1233. addr_list => '@',
  1234. ];
  1235. Which creates object methods of those names and types.
  1236. It even creates a new() method for us.
  1237. We could also have implemented our object this way:
  1238. struct 'Net::hostent' => { # note brace
  1239. name => '$',
  1240. aliases => '@',
  1241. addrtype => '$',
  1242. 'length' => '$',
  1243. addr_list => '@',
  1244. };
  1245. and then Class::Struct would have used an anonymous hash as the object
  1246. type, instead of an anonymous array. The array is faster and smaller,
  1247. but the hash works out better if you eventually want to do inheritance.
  1248. Since for this struct-like object we aren't planning on inheritance,
  1249. this time we'll opt for better speed and size over better flexibility.
  1250. Here's the whole implementation:
  1251. package Net::hostent;
  1252. use strict;
  1253. BEGIN {
  1254. use Exporter ();
  1255. our @EXPORT = qw(gethostbyname gethostbyaddr gethost);
  1256. our @EXPORT_OK = qw(
  1257. $h_name @h_aliases
  1258. $h_addrtype $h_length
  1259. @h_addr_list $h_addr
  1260. );
  1261. our %EXPORT_TAGS = ( FIELDS => [ @EXPORT_OK, @EXPORT ] );
  1262. }
  1263. our @EXPORT_OK;
  1264. # Class::Struct forbids use of @ISA
  1265. sub import { goto &Exporter::import }
  1266. use Class::Struct qw(struct);
  1267. struct 'Net::hostent' => [
  1268. name => '$',
  1269. aliases => '@',
  1270. addrtype => '$',
  1271. 'length' => '$',
  1272. addr_list => '@',
  1273. ];
  1274. sub addr { shift->addr_list->[0] }
  1275. sub populate (@) {
  1276. return unless @_;
  1277. my $hob = new(); # Class::Struct made this!
  1278. $h_name = $hob->[0] = $_[0];
  1279. @h_aliases = @{ $hob->[1] } = split ' ', $_[1];
  1280. $h_addrtype = $hob->[2] = $_[2];
  1281. $h_length = $hob->[3] = $_[3];
  1282. $h_addr = $_[4];
  1283. @h_addr_list = @{ $hob->[4] } = @_[ (4 .. $#_) ];
  1284. return $hob;
  1285. }
  1286. sub gethostbyname ($) { populate(CORE::gethostbyname(shift)) }
  1287. sub gethostbyaddr ($;$) {
  1288. my ($addr, $addrtype);
  1289. $addr = shift;
  1290. require Socket unless @_;
  1291. $addrtype = @_ ? shift : Socket::AF_INET();
  1292. populate(CORE::gethostbyaddr($addr, $addrtype))
  1293. }
  1294. sub gethost($) {
  1295. if ($_[0] =~ /^\d+(?:\.\d+(?:\.\d+(?:\.\d+)?)?)?$/) {
  1296. require Socket;
  1297. &gethostbyaddr(Socket::inet_aton(shift));
  1298. } else {
  1299. &gethostbyname;
  1300. }
  1301. }
  1302. 1;
  1303. We've snuck in quite a fair bit of other concepts besides just dynamic
  1304. class creation, like overriding core functions, import/export bits,
  1305. function prototyping, short-cut function call via C<&whatever>, and
  1306. function replacement with C<goto &whatever>. These all mostly make
  1307. sense from the perspective of a traditional module, but as you can see,
  1308. we can also use them in an object module.
  1309. You can look at other object-based, struct-like overrides of core
  1310. functions in the 5.004 release of Perl in File::stat, Net::hostent,
  1311. Net::netent, Net::protoent, Net::servent, Time::gmtime, Time::localtime,
  1312. User::grent, and User::pwent. These modules have a final component
  1313. that's all lowercase, by convention reserved for compiler pragmas,
  1314. because they affect the compilation and change a builtin function.
  1315. They also have the type names that a C programmer would most expect.
  1316. =head2 Data Members as Variables
  1317. If you're used to C++ objects, then you're accustomed to being able to
  1318. get at an object's data members as simple variables from within a method.
  1319. The Alias module provides for this, as well as a good bit more, such
  1320. as the possibility of private methods that the object can call but folks
  1321. outside the class cannot.
  1322. Here's an example of creating a Person using the Alias module.
  1323. When you update these magical instance variables, you automatically
  1324. update value fields in the hash. Convenient, eh?
  1325. package Person;
  1326. # this is the same as before...
  1327. sub new {
  1328. my $that = shift;
  1329. my $class = ref($that) || $that;
  1330. my $self = {
  1331. NAME => undef,
  1332. AGE => undef,
  1333. PEERS => [],
  1334. };
  1335. bless($self, $class);
  1336. return $self;
  1337. }
  1338. use Alias qw(attr);
  1339. our ($NAME, $AGE, $PEERS);
  1340. sub name {
  1341. my $self = attr shift;
  1342. if (@_) { $NAME = shift; }
  1343. return $NAME;
  1344. }
  1345. sub age {
  1346. my $self = attr shift;
  1347. if (@_) { $AGE = shift; }
  1348. return $AGE;
  1349. }
  1350. sub peers {
  1351. my $self = attr shift;
  1352. if (@_) { @PEERS = @_; }
  1353. return @PEERS;
  1354. }
  1355. sub exclaim {
  1356. my $self = attr shift;
  1357. return sprintf "Hi, I'm %s, age %d, working with %s",
  1358. $NAME, $AGE, join(", ", @PEERS);
  1359. }
  1360. sub happy_birthday {
  1361. my $self = attr shift;
  1362. return ++$AGE;
  1363. }
  1364. The need for the C<our> declaration is because what Alias does
  1365. is play with package globals with the same name as the fields. To use
  1366. globals while C<use strict> is in effect, you have to predeclare them.
  1367. These package variables are localized to the block enclosing the attr()
  1368. call just as if you'd used a local() on them. However, that means that
  1369. they're still considered global variables with temporary values, just
  1370. as with any other local().
  1371. It would be nice to combine Alias with
  1372. something like Class::Struct or Class::MethodMaker.
  1373. =head1 NOTES
  1374. =head2 Object Terminology
  1375. In the various OO literature, it seems that a lot of different words
  1376. are used to describe only a few different concepts. If you're not
  1377. already an object programmer, then you don't need to worry about all
  1378. these fancy words. But if you are, then you might like to know how to
  1379. get at the same concepts in Perl.
  1380. For example, it's common to call an object an I<instance> of a class
  1381. and to call those objects' methods I<instance methods>. Data fields
  1382. peculiar to each object are often called I<instance data> or I<object
  1383. attributes>, and data fields common to all members of that class are
  1384. I<class data>, I<class attributes>, or I<static data members>.
  1385. Also, I<base class>, I<generic class>, and I<superclass> all describe
  1386. the same notion, whereas I<derived class>, I<specific class>, and
  1387. I<subclass> describe the other related one.
  1388. C++ programmers have I<static methods> and I<virtual methods>,
  1389. but Perl only has I<class methods> and I<object methods>.
  1390. Actually, Perl only has methods. Whether a method gets used
  1391. as a class or object method is by usage only. You could accidentally
  1392. call a class method (one expecting a string argument) on an
  1393. object (one expecting a reference), or vice versa.
  1394. From the C++ perspective, all methods in Perl are virtual.
  1395. This, by the way, is why they are never checked for function
  1396. prototypes in the argument list as regular builtin and user-defined
  1397. functions can be.
  1398. Because a class is itself something of an object, Perl's classes can be
  1399. taken as describing both a "class as meta-object" (also called I<object
  1400. factory>) philosophy and the "class as type definition" (I<declaring>
  1401. behaviour, not I<defining> mechanism) idea. C++ supports the latter
  1402. notion, but not the former.
  1403. =head1 SEE ALSO
  1404. The following manpages will doubtless provide more
  1405. background for this one:
  1406. L<perlmod>,
  1407. L<perlref>,
  1408. L<perlobj>,
  1409. L<perlbot>,
  1410. L<perltie>,
  1411. and
  1412. L<overload>.
  1413. L<perlboot> is a kinder, gentler introduction to object-oriented
  1414. programming.
  1415. L<perltootc> provides more detail on class data.
  1416. Some modules which might prove interesting are Class::Accessor,
  1417. Class::Class, Class::Contract, Class::Data::Inheritable,
  1418. Class::MethodMaker and Tie::SecureHash
  1419. =head1 AUTHOR AND COPYRIGHT
  1420. Copyright (c) 1997, 1998 Tom Christiansen
  1421. All rights reserved.
  1422. When included as part of the Standard Version of Perl, or as part of
  1423. its complete documentation whether printed or otherwise, this work
  1424. may be distributed only under the terms of Perl's Artistic License.
  1425. Any distribution of this file or derivatives thereof I<outside>
  1426. of that package require that special arrangements be made with
  1427. copyright holder.
  1428. Irrespective of its distribution, all code examples in this file
  1429. are hereby placed into the public domain. You are permitted and
  1430. encouraged to use this code in your own programs for fun
  1431. or for profit as you see fit. A simple comment in the code giving
  1432. credit would be courteous but is not required.
  1433. =head1 COPYRIGHT
  1434. =head2 Acknowledgments
  1435. Thanks to
  1436. Larry Wall,
  1437. Roderick Schertler,
  1438. Gurusamy Sarathy,
  1439. Dean Roehrich,
  1440. Raphael Manfredi,
  1441. Brent Halsey,
  1442. Greg Bacon,
  1443. Brad Appleton,
  1444. and many others for their helpful comments.