Initial commit of OpenSPARC T2 architecture model.
[OpenSPARC-T2-SAM] / sam-t2 / devtools / v9 / man / man1 / perltoot.1
CommitLineData
920dae64
AT
1.\" Automatically generated by Pod::Man v1.37, Pod::Parser v1.32
2.\"
3.\" Standard preamble:
4.\" ========================================================================
5.de Sh \" Subsection heading
6.br
7.if t .Sp
8.ne 5
9.PP
10\fB\\$1\fR
11.PP
12..
13.de Sp \" Vertical space (when we can't use .PP)
14.if t .sp .5v
15.if n .sp
16..
17.de Vb \" Begin verbatim text
18.ft CW
19.nf
20.ne \\$1
21..
22.de Ve \" End verbatim text
23.ft R
24.fi
25..
26.\" Set up some character translations and predefined strings. \*(-- will
27.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
28.\" double quote, and \*(R" will give a right double quote. | will give a
29.\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to
30.\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C'
31.\" expand to `' in nroff, nothing in troff, for use with C<>.
32.tr \(*W-|\(bv\*(Tr
33.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
34.ie n \{\
35. ds -- \(*W-
36. ds PI pi
37. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
38. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
39. ds L" ""
40. ds R" ""
41. ds C` ""
42. ds C' ""
43'br\}
44.el\{\
45. ds -- \|\(em\|
46. ds PI \(*p
47. ds L" ``
48. ds R" ''
49'br\}
50.\"
51.\" If the F register is turned on, we'll generate index entries on stderr for
52.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
53.\" entries marked with X<> in POD. Of course, you'll have to process the
54.\" output yourself in some meaningful fashion.
55.if \nF \{\
56. de IX
57. tm Index:\\$1\t\\n%\t"\\$2"
58..
59. nr % 0
60. rr F
61.\}
62.\"
63.\" For nroff, turn off justification. Always turn off hyphenation; it makes
64.\" way too many mistakes in technical documents.
65.hy 0
66.if n .na
67.\"
68.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
69.\" Fear. Run. Save yourself. No user-serviceable parts.
70. \" fudge factors for nroff and troff
71.if n \{\
72. ds #H 0
73. ds #V .8m
74. ds #F .3m
75. ds #[ \f1
76. ds #] \fP
77.\}
78.if t \{\
79. ds #H ((1u-(\\\\n(.fu%2u))*.13m)
80. ds #V .6m
81. ds #F 0
82. ds #[ \&
83. ds #] \&
84.\}
85. \" simple accents for nroff and troff
86.if n \{\
87. ds ' \&
88. ds ` \&
89. ds ^ \&
90. ds , \&
91. ds ~ ~
92. ds /
93.\}
94.if t \{\
95. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
96. ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
97. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
98. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
99. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
100. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
101.\}
102. \" troff and (daisy-wheel) nroff accents
103.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
104.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
105.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
106.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
107.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
108.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
109.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
110.ds ae a\h'-(\w'a'u*4/10)'e
111.ds Ae A\h'-(\w'A'u*4/10)'E
112. \" corrections for vroff
113.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
114.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
115. \" for low resolution devices (crt and lpr)
116.if \n(.H>23 .if \n(.V>19 \
117\{\
118. ds : e
119. ds 8 ss
120. ds o a
121. ds d- d\h'-1'\(ga
122. ds D- D\h'-1'\(hy
123. ds th \o'bp'
124. ds Th \o'LP'
125. ds ae ae
126. ds Ae AE
127.\}
128.rm #[ #] #H #V #F C
129.\" ========================================================================
130.\"
131.IX Title "PERLTOOT 1"
132.TH PERLTOOT 1 "2006-01-07" "perl v5.8.8" "Perl Programmers Reference Guide"
133.SH "NAME"
134perltoot \- Tom's object\-oriented tutorial for perl
135.SH "DESCRIPTION"
136.IX Header "DESCRIPTION"
137Object-oriented programming is a big seller these days. Some managers
138would rather have objects than sliced bread. Why is that? What's so
139special about an object? Just what \fIis\fR an object anyway?
140.PP
141An object is nothing but a way of tucking away complex behaviours into
142a neat little easy-to-use bundle. (This is what professors call
143abstraction.) Smart people who have nothing to do but sit around for
144weeks on end figuring out really hard problems make these nifty
145objects that even regular people can use. (This is what professors call
146software reuse.) Users (well, programmers) can play with this little
147bundle all they want, but they aren't to open it up and mess with the
148insides. Just like an expensive piece of hardware, the contract says
149that you void the warranty if you muck with the cover. So don't do that.
150.PP
151The heart of objects is the class, a protected little private namespace
152full of data and functions. A class is a set of related routines that
153addresses some problem area. You can think of it as a user-defined type.
154The Perl package mechanism, also used for more traditional modules,
155is used for class modules as well. Objects \*(L"live\*(R" in a class, meaning
156that they belong to some package.
157.PP
158More often than not, the class provides the user with little bundles.
159These bundles are objects. They know whose class they belong to,
160and how to behave. Users ask the class to do something, like \*(L"give
161me an object.\*(R" Or they can ask one of these objects to do something.
162Asking a class to do something for you is calling a \fIclass method\fR.
163Asking an object to do something for you is calling an \fIobject method\fR.
164Asking either a class (usually) or an object (sometimes) to give you
165back an object is calling a \fIconstructor\fR, which is just a
166kind of method.
167.PP
168That's all well and good, but how is an object different from any other
169Perl data type? Just what is an object \fIreally\fR; that is, what's its
170fundamental type? The answer to the first question is easy. An object
171is different from any other data type in Perl in one and only one way:
172you may dereference it using not merely string or numeric subscripts
173as with simple arrays and hashes, but with named subroutine calls.
174In a word, with \fImethods\fR.
175.PP
176The answer to the second question is that it's a reference, and not just
177any reference, mind you, but one whose referent has been \fIbless\fR()ed
178into a particular class (read: package). What kind of reference? Well,
179the answer to that one is a bit less concrete. That's because in Perl
180the designer of the class can employ any sort of reference they'd like
181as the underlying intrinsic data type. It could be a scalar, an array,
182or a hash reference. It could even be a code reference. But because
183of its inherent flexibility, an object is usually a hash reference.
184.SH "Creating a Class"
185.IX Header "Creating a Class"
186Before you create a class, you need to decide what to name it. That's
187because the class (package) name governs the name of the file used to
188house it, just as with regular modules. Then, that class (package)
189should provide one or more ways to generate objects. Finally, it should
190provide mechanisms to allow users of its objects to indirectly manipulate
191these objects from a distance.
192.PP
193For example, let's make a simple Person class module. It gets stored in
194the file Person.pm. If it were called a Happy::Person class, it would
195be stored in the file Happy/Person.pm, and its package would become
196Happy::Person instead of just Person. (On a personal computer not
197running Unix or Plan 9, but something like Mac \s-1OS\s0 or \s-1VMS\s0, the directory
198separator may be different, but the principle is the same.) Do not assume
199any formal relationship between modules based on their directory names.
200This is merely a grouping convenience, and has no effect on inheritance,
201variable accessibility, or anything else.
202.PP
203For this module we aren't going to use Exporter, because we're
204a well-behaved class module that doesn't export anything at all.
205In order to manufacture objects, a class needs to have a \fIconstructor
206method\fR. A constructor gives you back not just a regular data type,
207but a brand-new object in that class. This magic is taken care of by
208the \fIbless()\fR function, whose sole purpose is to enable its referent to
209be used as an object. Remember: being an object really means nothing
210more than that methods may now be called against it.
211.PP
212While a constructor may be named anything you'd like, most Perl
213programmers seem to like to call theirs \fInew()\fR. However, \fInew()\fR is not
214a reserved word, and a class is under no obligation to supply such.
215Some programmers have also been known to use a function with
216the same name as the class as the constructor.
217.Sh "Object Representation"
218.IX Subsection "Object Representation"
219By far the most common mechanism used in Perl to represent a Pascal
220record, a C struct, or a \*(C+ class is an anonymous hash. That's because a
221hash has an arbitrary number of data fields, each conveniently accessed by
222an arbitrary name of your own devising.
223.PP
224If you were just doing a simple
225struct-like emulation, you would likely go about it something like this:
226.PP
227.Vb 5
228\& $rec = {
229\& name => "Jason",
230\& age => 23,
231\& peers => [ "Norbert", "Rhys", "Phineas"],
232\& };
233.Ve
234.PP
235If you felt like it, you could add a bit of visual distinction
236by up-casing the hash keys:
237.PP
238.Vb 5
239\& $rec = {
240\& NAME => "Jason",
241\& AGE => 23,
242\& PEERS => [ "Norbert", "Rhys", "Phineas"],
243\& };
244.Ve
245.PP
246And so you could get at \f(CW\*(C`$rec\->{NAME}\*(C'\fR to find \*(L"Jason\*(R", or
247\&\f(CW\*(C`@{ $rec\->{PEERS} }\*(C'\fR to get at \*(L"Norbert\*(R", \*(L"Rhys\*(R", and \*(L"Phineas\*(R".
248(Have you ever noticed how many 23\-year\-old programmers seem to
249be named \*(L"Jason\*(R" these days? :\-)
250.PP
251This same model is often used for classes, although it is not considered
252the pinnacle of programming propriety for folks from outside the
253class to come waltzing into an object, brazenly accessing its data
254members directly. Generally speaking, an object should be considered
255an opaque cookie that you use \fIobject methods\fR to access. Visually,
256methods look like you're dereffing a reference using a function name
257instead of brackets or braces.
258.Sh "Class Interface"
259.IX Subsection "Class Interface"
260Some languages provide a formal syntactic interface to a class's methods,
261but Perl does not. It relies on you to read the documentation of each
262class. If you try to call an undefined method on an object, Perl won't
263complain, but the program will trigger an exception while it's running.
264Likewise, if you call a method expecting a prime number as its argument
265with a non-prime one instead, you can't expect the compiler to catch this.
266(Well, you can expect it all you like, but it's not going to happen.)
267.PP
268Let's suppose you have a well-educated user of your Person class,
269someone who has read the docs that explain the prescribed
270interface. Here's how they might use the Person class:
271.PP
272.Vb 1
273\& use Person;
274.Ve
275.PP
276.Vb 4
277\& $him = Person->new();
278\& $him->name("Jason");
279\& $him->age(23);
280\& $him->peers( "Norbert", "Rhys", "Phineas" );
281.Ve
282.PP
283.Vb 1
284\& push @All_Recs, $him; # save object in array for later
285.Ve
286.PP
287.Vb 2
288\& printf "%s is %d years old.\en", $him->name, $him->age;
289\& print "His peers are: ", join(", ", $him->peers), "\en";
290.Ve
291.PP
292.Vb 1
293\& printf "Last rec's name is %s\en", $All_Recs[-1]->name;
294.Ve
295.PP
296As you can see, the user of the class doesn't know (or at least, has no
297business paying attention to the fact) that the object has one particular
298implementation or another. The interface to the class and its objects
299is exclusively via methods, and that's all the user of the class should
300ever play with.
301.Sh "Constructors and Instance Methods"
302.IX Subsection "Constructors and Instance Methods"
303Still, \fIsomeone\fR has to know what's in the object. And that someone is
304the class. It implements methods that the programmer uses to access
305the object. Here's how to implement the Person class using the standard
306hash-ref-as-an-object idiom. We'll make a class method called \fInew()\fR to
307act as the constructor, and three object methods called \fIname()\fR, \fIage()\fR, and
308\&\fIpeers()\fR to get at per-object data hidden away in our anonymous hash.
309.PP
310.Vb 2
311\& package Person;
312\& use strict;
313.Ve
314.PP
315.Vb 11
316\& ##################################################
317\& ## the object constructor (simplistic version) ##
318\& ##################################################
319\& sub new {
320\& my $self = {};
321\& $self->{NAME} = undef;
322\& $self->{AGE} = undef;
323\& $self->{PEERS} = [];
324\& bless($self); # but see below
325\& return $self;
326\& }
327.Ve
328.PP
329.Vb 6
330\& ##############################################
331\& ## methods to access per-object data ##
332\& ## ##
333\& ## With args, they set the value. Without ##
334\& ## any, they only retrieve it/them. ##
335\& ##############################################
336.Ve
337.PP
338.Vb 5
339\& sub name {
340\& my $self = shift;
341\& if (@_) { $self->{NAME} = shift }
342\& return $self->{NAME};
343\& }
344.Ve
345.PP
346.Vb 5
347\& sub age {
348\& my $self = shift;
349\& if (@_) { $self->{AGE} = shift }
350\& return $self->{AGE};
351\& }
352.Ve
353.PP
354.Vb 5
355\& sub peers {
356\& my $self = shift;
357\& if (@_) { @{ $self->{PEERS} } = @_ }
358\& return @{ $self->{PEERS} };
359\& }
360.Ve
361.PP
362.Vb 1
363\& 1; # so the require or use succeeds
364.Ve
365.PP
366We've created three methods to access an object's data, \fIname()\fR, \fIage()\fR,
367and \fIpeers()\fR. These are all substantially similar. If called with an
368argument, they set the appropriate field; otherwise they return the
369value held by that field, meaning the value of that hash key.
370.Sh "Planning for the Future: Better Constructors"
371.IX Subsection "Planning for the Future: Better Constructors"
372Even though at this point you may not even know what it means, someday
373you're going to worry about inheritance. (You can safely ignore this
374for now and worry about it later if you'd like.) To ensure that this
375all works out smoothly, you must use the double-argument form of \fIbless()\fR.
376The second argument is the class into which the referent will be blessed.
377By not assuming our own class as the default second argument and instead
378using the class passed into us, we make our constructor inheritable.
379.PP
380.Vb 9
381\& sub new {
382\& my $class = shift;
383\& my $self = {};
384\& $self->{NAME} = undef;
385\& $self->{AGE} = undef;
386\& $self->{PEERS} = [];
387\& bless ($self, $class);
388\& return $self;
389\& }
390.Ve
391.PP
392That's about all there is for constructors. These methods bring objects
393to life, returning neat little opaque bundles to the user to be used in
394subsequent method calls.
395.Sh "Destructors"
396.IX Subsection "Destructors"
397Every story has a beginning and an end. The beginning of the object's
398story is its constructor, explicitly called when the object comes into
399existence. But the ending of its story is the \fIdestructor\fR, a method
400implicitly called when an object leaves this life. Any per-object
401clean-up code is placed in the destructor, which must (in Perl) be called
402\&\s-1DESTROY\s0.
403.PP
404If constructors can have arbitrary names, then why not destructors?
405Because while a constructor is explicitly called, a destructor is not.
406Destruction happens automatically via Perl's garbage collection (\s-1GC\s0)
407system, which is a quick but somewhat lazy reference-based \s-1GC\s0 system.
408To know what to call, Perl insists that the destructor be named \s-1DESTROY\s0.
409Perl's notion of the right time to call a destructor is not well-defined
410currently, which is why your destructors should not rely on when they are
411called.
412.PP
413Why is \s-1DESTROY\s0 in all caps? Perl on occasion uses purely uppercase
414function names as a convention to indicate that the function will
415be automatically called by Perl in some way. Others that are called
416implicitly include \s-1BEGIN\s0, \s-1END\s0, \s-1AUTOLOAD\s0, plus all methods used by
417tied objects, described in perltie.
418.PP
419In really good object-oriented programming languages, the user doesn't
420care when the destructor is called. It just happens when it's supposed
421to. In low-level languages without any \s-1GC\s0 at all, there's no way to
422depend on this happening at the right time, so the programmer must
423explicitly call the destructor to clean up memory and state, crossing
424their fingers that it's the right time to do so. Unlike \*(C+, an
425object destructor is nearly never needed in Perl, and even when it is,
426explicit invocation is uncalled for. In the case of our Person class,
427we don't need a destructor because Perl takes care of simple matters
428like memory deallocation.
429.PP
430The only situation where Perl's reference-based \s-1GC\s0 won't work is
431when there's a circularity in the data structure, such as:
432.PP
433.Vb 1
434\& $this->{WHATEVER} = $this;
435.Ve
436.PP
437In that case, you must delete the self-reference manually if you expect
438your program not to leak memory. While admittedly error\-prone, this is
439the best we can do right now. Nonetheless, rest assured that when your
440program is finished, its objects' destructors are all duly called.
441So you are guaranteed that an object \fIeventually\fR gets properly
442destroyed, except in the unique case of a program that never exits.
443(If you're running Perl embedded in another application, this full \s-1GC\s0
444pass happens a bit more frequently\*(--whenever a thread shuts down.)
445.Sh "Other Object Methods"
446.IX Subsection "Other Object Methods"
447The methods we've talked about so far have either been constructors or
448else simple \*(L"data methods\*(R", interfaces to data stored in the object.
449These are a bit like an object's data members in the \*(C+ world, except
450that strangers don't access them as data. Instead, they should only
451access the object's data indirectly via its methods. This is an
452important rule: in Perl, access to an object's data should \fIonly\fR
453be made through methods.
454.PP
455Perl doesn't impose restrictions on who gets to use which methods.
456The public-versus-private distinction is by convention, not syntax.
457(Well, unless you use the Alias module described below in
458\&\*(L"Data Members as Variables\*(R".) Occasionally you'll see method names beginning or ending
459with an underscore or two. This marking is a convention indicating
460that the methods are private to that class alone and sometimes to its
461closest acquaintances, its immediate subclasses. But this distinction
462is not enforced by Perl itself. It's up to the programmer to behave.
463.PP
464There's no reason to limit methods to those that simply access data.
465Methods can do anything at all. The key point is that they're invoked
466against an object or a class. Let's say we'd like object methods that
467do more than fetch or set one particular field.
468.PP
469.Vb 5
470\& sub exclaim {
471\& my $self = shift;
472\& return sprintf "Hi, I'm %s, age %d, working with %s",
473\& $self->{NAME}, $self->{AGE}, join(", ", @{$self->{PEERS}});
474\& }
475.Ve
476.PP
477Or maybe even one like this:
478.PP
479.Vb 4
480\& sub happy_birthday {
481\& my $self = shift;
482\& return ++$self->{AGE};
483\& }
484.Ve
485.PP
486Some might argue that one should go at these this way:
487.PP
488.Vb 5
489\& sub exclaim {
490\& my $self = shift;
491\& return sprintf "Hi, I'm %s, age %d, working with %s",
492\& $self->name, $self->age, join(", ", $self->peers);
493\& }
494.Ve
495.PP
496.Vb 4
497\& sub happy_birthday {
498\& my $self = shift;
499\& return $self->age( $self->age() + 1 );
500\& }
501.Ve
502.PP
503But since these methods are all executing in the class itself, this
504may not be critical. There are tradeoffs to be made. Using direct
505hash access is faster (about an order of magnitude faster, in fact), and
506it's more convenient when you want to interpolate in strings. But using
507methods (the external interface) internally shields not just the users of
508your class but even you yourself from changes in your data representation.
509.SH "Class Data"
510.IX Header "Class Data"
511What about \*(L"class data\*(R", data items common to each object in a class?
512What would you want that for? Well, in your Person class, you might
513like to keep track of the total people alive. How do you implement that?
514.PP
515You \fIcould\fR make it a global variable called \f(CW$Person::Census\fR. But about
516only reason you'd do that would be if you \fIwanted\fR people to be able to
517get at your class data directly. They could just say \f(CW$Person::Census\fR
518and play around with it. Maybe this is ok in your design scheme.
519You might even conceivably want to make it an exported variable. To be
520exportable, a variable must be a (package) global. If this were a
521traditional module rather than an object-oriented one, you might do that.
522.PP
523While this approach is expected in most traditional modules, it's
524generally considered rather poor form in most object modules. In an
525object module, you should set up a protective veil to separate interface
526from implementation. So provide a class method to access class data
527just as you provide object methods to access object data.
528.PP
529So, you \fIcould\fR still keep \f(CW$Census\fR as a package global and rely upon
530others to honor the contract of the module and therefore not play around
531with its implementation. You could even be supertricky and make \f(CW$Census\fR a
532tied object as described in perltie, thereby intercepting all accesses.
533.PP
534But more often than not, you just want to make your class data a
535file-scoped lexical. To do so, simply put this at the top of the file:
536.PP
537.Vb 1
538\& my $Census = 0;
539.Ve
540.PP
541Even though the scope of a \fImy()\fR normally expires when the block in which
542it was declared is done (in this case the whole file being required or
543used), Perl's deep binding of lexical variables guarantees that the
544variable will not be deallocated, remaining accessible to functions
545declared within that scope. This doesn't work with global variables
546given temporary values via \fIlocal()\fR, though.
547.PP
548Irrespective of whether you leave \f(CW$Census\fR a package global or make
549it instead a file-scoped lexical, you should make these
550changes to your \fIPerson::new()\fR constructor:
551.PP
552.Vb 10
553\& sub new {
554\& my $class = shift;
555\& my $self = {};
556\& $Census++;
557\& $self->{NAME} = undef;
558\& $self->{AGE} = undef;
559\& $self->{PEERS} = [];
560\& bless ($self, $class);
561\& return $self;
562\& }
563.Ve
564.PP
565.Vb 3
566\& sub population {
567\& return $Census;
568\& }
569.Ve
570.PP
571Now that we've done this, we certainly do need a destructor so that
572when Person is destroyed, the \f(CW$Census\fR goes down. Here's how
573this could be done:
574.PP
575.Vb 1
576\& sub DESTROY { --$Census }
577.Ve
578.PP
579Notice how there's no memory to deallocate in the destructor? That's
580something that Perl takes care of for you all by itself.
581.PP
582Alternatively, you could use the Class::Data::Inheritable module from
583\&\s-1CPAN\s0.
584.Sh "Accessing Class Data"
585.IX Subsection "Accessing Class Data"
586It turns out that this is not really a good way to go about handling
587class data. A good scalable rule is that \fIyou must never reference class
588data directly from an object method\fR. Otherwise you aren't building a
589scalable, inheritable class. The object must be the rendezvous point
590for all operations, especially from an object method. The globals
591(class data) would in some sense be in the \*(L"wrong\*(R" package in your
592derived classes. In Perl, methods execute in the context of the class
593they were defined in, \fInot\fR that of the object that triggered them.
594Therefore, namespace visibility of package globals in methods is unrelated
595to inheritance.
596.PP
597Got that? Maybe not. Ok, let's say that some other class \*(L"borrowed\*(R"
598(well, inherited) the \s-1DESTROY\s0 method as it was defined above. When those
599objects are destroyed, the original \f(CW$Census\fR variable will be altered,
600not the one in the new class's package namespace. Perhaps this is what
601you want, but probably it isn't.
602.PP
603Here's how to fix this. We'll store a reference to the data in the
604value accessed by the hash key \*(L"_CENSUS\*(R". Why the underscore? Well,
605mostly because an initial underscore already conveys strong feelings
606of magicalness to a C programmer. It's really just a mnemonic device
607to remind ourselves that this field is special and not to be used as
608a public data member in the same way that \s-1NAME\s0, \s-1AGE\s0, and \s-1PEERS\s0 are.
609(Because we've been developing this code under the strict pragma, prior
610to perl version 5.004 we'll have to quote the field name.)
611.PP
612.Vb 12
613\& sub new {
614\& my $class = shift;
615\& my $self = {};
616\& $self->{NAME} = undef;
617\& $self->{AGE} = undef;
618\& $self->{PEERS} = [];
619\& # "private" data
620\& $self->{"_CENSUS"} = \e$Census;
621\& bless ($self, $class);
622\& ++ ${ $self->{"_CENSUS"} };
623\& return $self;
624\& }
625.Ve
626.PP
627.Vb 8
628\& sub population {
629\& my $self = shift;
630\& if (ref $self) {
631\& return ${ $self->{"_CENSUS"} };
632\& } else {
633\& return $Census;
634\& }
635\& }
636.Ve
637.PP
638.Vb 4
639\& sub DESTROY {
640\& my $self = shift;
641\& -- ${ $self->{"_CENSUS"} };
642\& }
643.Ve
644.Sh "Debugging Methods"
645.IX Subsection "Debugging Methods"
646It's common for a class to have a debugging mechanism. For example,
647you might want to see when objects are created or destroyed. To do that,
648add a debugging variable as a file-scoped lexical. For this, we'll pull
649in the standard Carp module to emit our warnings and fatal messages.
650That way messages will come out with the caller's filename and
651line number instead of our own; if we wanted them to be from our own
652perspective, we'd just use \fIdie()\fR and \fIwarn()\fR directly instead of \fIcroak()\fR
653and \fIcarp()\fR respectively.
654.PP
655.Vb 2
656\& use Carp;
657\& my $Debugging = 0;
658.Ve
659.PP
660Now add a new class method to access the variable.
661.PP
662.Vb 6
663\& sub debug {
664\& my $class = shift;
665\& if (ref $class) { confess "Class method called as object method" }
666\& unless (@_ == 1) { confess "usage: CLASSNAME->debug(level)" }
667\& $Debugging = shift;
668\& }
669.Ve
670.PP
671Now fix up \s-1DESTROY\s0 to murmur a bit as the moribund object expires:
672.PP
673.Vb 5
674\& sub DESTROY {
675\& my $self = shift;
676\& if ($Debugging) { carp "Destroying $self " . $self->name }
677\& -- ${ $self->{"_CENSUS"} };
678\& }
679.Ve
680.PP
681One could conceivably make a per-object debug state. That
682way you could call both of these:
683.PP
684.Vb 2
685\& Person->debug(1); # entire class
686\& $him->debug(1); # just this object
687.Ve
688.PP
689To do so, we need our debugging method to be a \*(L"bimodal\*(R" one, one that
690works on both classes \fIand\fR objects. Therefore, adjust the \fIdebug()\fR
691and \s-1DESTROY\s0 methods as follows:
692.PP
693.Vb 10
694\& sub debug {
695\& my $self = shift;
696\& confess "usage: thing->debug(level)" unless @_ == 1;
697\& my $level = shift;
698\& if (ref($self)) {
699\& $self->{"_DEBUG"} = $level; # just myself
700\& } else {
701\& $Debugging = $level; # whole class
702\& }
703\& }
704.Ve
705.PP
706.Vb 7
707\& sub DESTROY {
708\& my $self = shift;
709\& if ($Debugging || $self->{"_DEBUG"}) {
710\& carp "Destroying $self " . $self->name;
711\& }
712\& -- ${ $self->{"_CENSUS"} };
713\& }
714.Ve
715.PP
716What happens if a derived class (which we'll call Employee) inherits
717methods from this Person base class? Then \f(CW\*(C`Employee\->debug()\*(C'\fR, when called
718as a class method, manipulates \f(CW$Person::Debugging\fR not \f(CW$Employee::Debugging\fR.
719.Sh "Class Destructors"
720.IX Subsection "Class Destructors"
721The object destructor handles the death of each distinct object. But sometimes
722you want a bit of cleanup when the entire class is shut down, which
723currently only happens when the program exits. To make such a
724\&\fIclass destructor\fR, create a function in that class's package named
725\&\s-1END\s0. This works just like the \s-1END\s0 function in traditional modules,
726meaning that it gets called whenever your program exits unless it execs
727or dies of an uncaught signal. For example,
728.PP
729.Vb 5
730\& sub END {
731\& if ($Debugging) {
732\& print "All persons are going away now.\en";
733\& }
734\& }
735.Ve
736.PP
737When the program exits, all the class destructors (\s-1END\s0 functions) are
738be called in the opposite order that they were loaded in (\s-1LIFO\s0 order).
739.Sh "Documenting the Interface"
740.IX Subsection "Documenting the Interface"
741And there you have it: we've just shown you the \fIimplementation\fR of this
742Person class. Its \fIinterface\fR would be its documentation. Usually this
743means putting it in pod (\*(L"plain old documentation\*(R") format right there
744in the same file. In our Person example, we would place the following
745docs anywhere in the Person.pm file. Even though it looks mostly like
746code, it's not. It's embedded documentation such as would be used by
747the pod2man, pod2html, or pod2text programs. The Perl compiler ignores
748pods entirely, just as the translators ignore code. Here's an example of
749some pods describing the informal interface:
750.PP
751.Vb 1
752\& =head1 NAME
753.Ve
754.PP
755.Vb 1
756\& Person - class to implement people
757.Ve
758.PP
759.Vb 1
760\& =head1 SYNOPSIS
761.Ve
762.PP
763.Vb 1
764\& use Person;
765.Ve
766.PP
767.Vb 5
768\& #################
769\& # class methods #
770\& #################
771\& $ob = Person->new;
772\& $count = Person->population;
773.Ve
774.PP
775.Vb 3
776\& #######################
777\& # object data methods #
778\& #######################
779.Ve
780.PP
781.Vb 4
782\& ### get versions ###
783\& $who = $ob->name;
784\& $years = $ob->age;
785\& @pals = $ob->peers;
786.Ve
787.PP
788.Vb 4
789\& ### set versions ###
790\& $ob->name("Jason");
791\& $ob->age(23);
792\& $ob->peers( "Norbert", "Rhys", "Phineas" );
793.Ve
794.PP
795.Vb 3
796\& ########################
797\& # other object methods #
798\& ########################
799.Ve
800.PP
801.Vb 2
802\& $phrase = $ob->exclaim;
803\& $ob->happy_birthday;
804.Ve
805.PP
806.Vb 1
807\& =head1 DESCRIPTION
808.Ve
809.PP
810.Vb 1
811\& The Person class implements dah dee dah dee dah....
812.Ve
813.PP
814That's all there is to the matter of interface versus implementation.
815A programmer who opens up the module and plays around with all the private
816little shiny bits that were safely locked up behind the interface contract
817has voided the warranty, and you shouldn't worry about their fate.
818.SH "Aggregation"
819.IX Header "Aggregation"
820Suppose you later want to change the class to implement better names.
821Perhaps you'd like to support both given names (called Christian names,
822irrespective of one's religion) and family names (called surnames), plus
823nicknames and titles. If users of your Person class have been properly
824accessing it through its documented interface, then you can easily change
825the underlying implementation. If they haven't, then they lose and
826it's their fault for breaking the contract and voiding their warranty.
827.PP
828To do this, we'll make another class, this one called Fullname. What's
829the Fullname class look like? To answer that question, you have to
830first figure out how you want to use it. How about we use it this way:
831.PP
832.Vb 7
833\& $him = Person->new();
834\& $him->fullname->title("St");
835\& $him->fullname->christian("Thomas");
836\& $him->fullname->surname("Aquinas");
837\& $him->fullname->nickname("Tommy");
838\& printf "His normal name is %s\en", $him->name;
839\& printf "But his real name is %s\en", $him->fullname->as_string;
840.Ve
841.PP
842Ok. To do this, we'll change \fIPerson::new()\fR so that it supports
843a full name field this way:
844.PP
845.Vb 11
846\& sub new {
847\& my $class = shift;
848\& my $self = {};
849\& $self->{FULLNAME} = Fullname->new();
850\& $self->{AGE} = undef;
851\& $self->{PEERS} = [];
852\& $self->{"_CENSUS"} = \e$Census;
853\& bless ($self, $class);
854\& ++ ${ $self->{"_CENSUS"} };
855\& return $self;
856\& }
857.Ve
858.PP
859.Vb 4
860\& sub fullname {
861\& my $self = shift;
862\& return $self->{FULLNAME};
863\& }
864.Ve
865.PP
866Then to support old code, define \fIPerson::name()\fR this way:
867.PP
868.Vb 5
869\& sub name {
870\& my $self = shift;
871\& return $self->{FULLNAME}->nickname(@_)
872\& || $self->{FULLNAME}->christian(@_);
873\& }
874.Ve
875.PP
876Here's the Fullname class. We'll use the same technique
877of using a hash reference to hold data fields, and methods
878by the appropriate name to access them:
879.PP
880.Vb 2
881\& package Fullname;
882\& use strict;
883.Ve
884.PP
885.Vb 11
886\& sub new {
887\& my $class = shift;
888\& my $self = {
889\& TITLE => undef,
890\& CHRISTIAN => undef,
891\& SURNAME => undef,
892\& NICK => undef,
893\& };
894\& bless ($self, $class);
895\& return $self;
896\& }
897.Ve
898.PP
899.Vb 5
900\& sub christian {
901\& my $self = shift;
902\& if (@_) { $self->{CHRISTIAN} = shift }
903\& return $self->{CHRISTIAN};
904\& }
905.Ve
906.PP
907.Vb 5
908\& sub surname {
909\& my $self = shift;
910\& if (@_) { $self->{SURNAME} = shift }
911\& return $self->{SURNAME};
912\& }
913.Ve
914.PP
915.Vb 5
916\& sub nickname {
917\& my $self = shift;
918\& if (@_) { $self->{NICK} = shift }
919\& return $self->{NICK};
920\& }
921.Ve
922.PP
923.Vb 5
924\& sub title {
925\& my $self = shift;
926\& if (@_) { $self->{TITLE} = shift }
927\& return $self->{TITLE};
928\& }
929.Ve
930.PP
931.Vb 8
932\& sub as_string {
933\& my $self = shift;
934\& my $name = join(" ", @$self{'CHRISTIAN', 'SURNAME'});
935\& if ($self->{TITLE}) {
936\& $name = $self->{TITLE} . " " . $name;
937\& }
938\& return $name;
939\& }
940.Ve
941.PP
942.Vb 1
943\& 1;
944.Ve
945.PP
946Finally, here's the test program:
947.PP
948.Vb 4
949\& #!/usr/bin/perl -w
950\& use strict;
951\& use Person;
952\& sub END { show_census() }
953.Ve
954.PP
955.Vb 3
956\& sub show_census () {
957\& printf "Current population: %d\en", Person->population;
958\& }
959.Ve
960.PP
961.Vb 1
962\& Person->debug(1);
963.Ve
964.PP
965.Vb 1
966\& show_census();
967.Ve
968.PP
969.Vb 1
970\& my $him = Person->new();
971.Ve
972.PP
973.Vb 5
974\& $him->fullname->christian("Thomas");
975\& $him->fullname->surname("Aquinas");
976\& $him->fullname->nickname("Tommy");
977\& $him->fullname->title("St");
978\& $him->age(1);
979.Ve
980.PP
981.Vb 4
982\& printf "%s is really %s.\en", $him->name, $him->fullname->as_string;
983\& printf "%s's age: %d.\en", $him->name, $him->age;
984\& $him->happy_birthday;
985\& printf "%s's age: %d.\en", $him->name, $him->age;
986.Ve
987.PP
988.Vb 1
989\& show_census();
990.Ve
991.SH "Inheritance"
992.IX Header "Inheritance"
993Object-oriented programming systems all support some notion of
994inheritance. Inheritance means allowing one class to piggy-back on
995top of another one so you don't have to write the same code again and
996again. It's about software reuse, and therefore related to Laziness,
997the principal virtue of a programmer. (The import/export mechanisms in
998traditional modules are also a form of code reuse, but a simpler one than
999the true inheritance that you find in object modules.)
1000.PP
1001Sometimes the syntax of inheritance is built into the core of the
1002language, and sometimes it's not. Perl has no special syntax for
1003specifying the class (or classes) to inherit from. Instead, it's all
1004strictly in the semantics. Each package can have a variable called \f(CW@ISA\fR,
1005which governs (method) inheritance. If you try to call a method on an
1006object or class, and that method is not found in that object's package,
1007Perl then looks to \f(CW@ISA\fR for other packages to go looking through in
1008search of the missing method.
1009.PP
1010Like the special per-package variables recognized by Exporter (such as
1011\&\f(CW@EXPORT\fR, \f(CW@EXPORT_OK\fR, \f(CW@EXPORT_FAIL\fR, \f(CW%EXPORT_TAGS\fR, and \f(CW$VERSION\fR), the \f(CW@ISA\fR
1012array \fImust\fR be a package-scoped global and not a file-scoped lexical
1013created via \fImy()\fR. Most classes have just one item in their \f(CW@ISA\fR array.
1014In this case, we have what's called \*(L"single inheritance\*(R", or \s-1SI\s0 for short.
1015.PP
1016Consider this class:
1017.PP
1018.Vb 4
1019\& package Employee;
1020\& use Person;
1021\& @ISA = ("Person");
1022\& 1;
1023.Ve
1024.PP
1025Not a lot to it, eh? All it's doing so far is loading in another
1026class and stating that this one will inherit methods from that
1027other class if need be. We have given it none of its own methods.
1028We rely upon an Employee to behave just like a Person.
1029.PP
1030Setting up an empty class like this is called the \*(L"empty subclass test\*(R";
1031that is, making a derived class that does nothing but inherit from a
1032base class. If the original base class has been designed properly,
1033then the new derived class can be used as a drop-in replacement for the
1034old one. This means you should be able to write a program like this:
1035.PP
1036.Vb 5
1037\& use Employee;
1038\& my $empl = Employee->new();
1039\& $empl->name("Jason");
1040\& $empl->age(23);
1041\& printf "%s is age %d.\en", $empl->name, $empl->age;
1042.Ve
1043.PP
1044By proper design, we mean always using the two-argument form of \fIbless()\fR,
1045avoiding direct access of global data, and not exporting anything. If you
1046look back at the \fIPerson::new()\fR function we defined above, we were careful
1047to do that. There's a bit of package data used in the constructor,
1048but the reference to this is stored on the object itself and all other
1049methods access package data via that reference, so we should be ok.
1050.PP
1051What do we mean by the \fIPerson::new()\fR function \*(-- isn't that actually
1052a method? Well, in principle, yes. A method is just a function that
1053expects as its first argument a class name (package) or object
1054(blessed reference). \fIPerson::new()\fR is the function that both the
1055\&\f(CW\*(C`Person\->new()\*(C'\fR method and the \f(CW\*(C`Employee\->new()\*(C'\fR method end
1056up calling. Understand that while a method call looks a lot like a
1057function call, they aren't really quite the same, and if you treat them
1058as the same, you'll very soon be left with nothing but broken programs.
1059First, the actual underlying calling conventions are different: method
1060calls get an extra argument. Second, function calls don't do inheritance,
1061but methods do.
1062.PP
1063.Vb 4
1064\& Method Call Resulting Function Call
1065\& ----------- ------------------------
1066\& Person->new() Person::new("Person")
1067\& Employee->new() Person::new("Employee")
1068.Ve
1069.PP
1070So don't use function calls when you mean to call a method.
1071.PP
1072If an employee is just a Person, that's not all too very interesting.
1073So let's add some other methods. We'll give our employee
1074data fields to access their salary, their employee \s-1ID\s0, and their
1075start date.
1076.PP
1077If you're getting a little tired of creating all these nearly identical
1078methods just to get at the object's data, do not despair. Later,
1079we'll describe several different convenience mechanisms for shortening
1080this up. Meanwhile, here's the straight-forward way:
1081.PP
1082.Vb 5
1083\& sub salary {
1084\& my $self = shift;
1085\& if (@_) { $self->{SALARY} = shift }
1086\& return $self->{SALARY};
1087\& }
1088.Ve
1089.PP
1090.Vb 5
1091\& sub id_number {
1092\& my $self = shift;
1093\& if (@_) { $self->{ID} = shift }
1094\& return $self->{ID};
1095\& }
1096.Ve
1097.PP
1098.Vb 5
1099\& sub start_date {
1100\& my $self = shift;
1101\& if (@_) { $self->{START_DATE} = shift }
1102\& return $self->{START_DATE};
1103\& }
1104.Ve
1105.Sh "Overridden Methods"
1106.IX Subsection "Overridden Methods"
1107What happens when both a derived class and its base class have the same
1108method defined? Well, then you get the derived class's version of that
1109method. For example, let's say that we want the \fIpeers()\fR method called on
1110an employee to act a bit differently. Instead of just returning the list
1111of peer names, let's return slightly different strings. So doing this:
1112.PP
1113.Vb 2
1114\& $empl->peers("Peter", "Paul", "Mary");
1115\& printf "His peers are: %s\en", join(", ", $empl->peers);
1116.Ve
1117.PP
1118will produce:
1119.PP
1120.Vb 1
1121\& His peers are: PEON=PETER, PEON=PAUL, PEON=MARY
1122.Ve
1123.PP
1124To do this, merely add this definition into the Employee.pm file:
1125.PP
1126.Vb 5
1127\& sub peers {
1128\& my $self = shift;
1129\& if (@_) { @{ $self->{PEERS} } = @_ }
1130\& return map { "PEON=\eU$_" } @{ $self->{PEERS} };
1131\& }
1132.Ve
1133.PP
1134There, we've just demonstrated the high\-falutin' concept known in certain
1135circles as \fIpolymorphism\fR. We've taken on the form and behaviour of
1136an existing object, and then we've altered it to suit our own purposes.
1137This is a form of Laziness. (Getting polymorphed is also what happens
1138when the wizard decides you'd look better as a frog.)
1139.PP
1140Every now and then you'll want to have a method call trigger both its
1141derived class (also known as \*(L"subclass\*(R") version as well as its base class
1142(also known as \*(L"superclass\*(R") version. In practice, constructors and
1143destructors are likely to want to do this, and it probably also makes
1144sense in the \fIdebug()\fR method we showed previously.
1145.PP
1146To do this, add this to Employee.pm:
1147.PP
1148.Vb 2
1149\& use Carp;
1150\& my $Debugging = 0;
1151.Ve
1152.PP
1153.Vb 11
1154\& sub debug {
1155\& my $self = shift;
1156\& confess "usage: thing->debug(level)" unless @_ == 1;
1157\& my $level = shift;
1158\& if (ref($self)) {
1159\& $self->{"_DEBUG"} = $level;
1160\& } else {
1161\& $Debugging = $level; # whole class
1162\& }
1163\& Person::debug($self, $Debugging); # don't really do this
1164\& }
1165.Ve
1166.PP
1167As you see, we turn around and call the Person package's \fIdebug()\fR function.
1168But this is far too fragile for good design. What if Person doesn't
1169have a \fIdebug()\fR function, but is inheriting \fIits\fR \fIdebug()\fR method
1170from elsewhere? It would have been slightly better to say
1171.PP
1172.Vb 1
1173\& Person->debug($Debugging);
1174.Ve
1175.PP
1176But even that's got too much hard\-coded. It's somewhat better to say
1177.PP
1178.Vb 1
1179\& $self->Person::debug($Debugging);
1180.Ve
1181.PP
1182Which is a funny way to say to start looking for a \fIdebug()\fR method up
1183in Person. This strategy is more often seen on overridden object methods
1184than on overridden class methods.
1185.PP
1186There is still something a bit off here. We've hard-coded our
1187superclass's name. This in particular is bad if you change which classes
1188you inherit from, or add others. Fortunately, the pseudoclass \s-1SUPER\s0
1189comes to the rescue here.
1190.PP
1191.Vb 1
1192\& $self->SUPER::debug($Debugging);
1193.Ve
1194.PP
1195This way it starts looking in my class's \f(CW@ISA\fR. This only makes sense
1196from \fIwithin\fR a method call, though. Don't try to access anything
1197in \s-1SUPER::\s0 from anywhere else, because it doesn't exist outside
1198an overridden method call. Note that \f(CW\*(C`SUPER\*(C'\fR refers to the superclass of
1199the current package, \fInot\fR to the superclass of \f(CW$self\fR.
1200.PP
1201Things are getting a bit complicated here. Have we done anything
1202we shouldn't? As before, one way to test whether we're designing
1203a decent class is via the empty subclass test. Since we already have
1204an Employee class that we're trying to check, we'd better get a new
1205empty subclass that can derive from Employee. Here's one:
1206.PP
1207.Vb 3
1208\& package Boss;
1209\& use Employee; # :-)
1210\& @ISA = qw(Employee);
1211.Ve
1212.PP
1213And here's the test program:
1214.PP
1215.Vb 4
1216\& #!/usr/bin/perl -w
1217\& use strict;
1218\& use Boss;
1219\& Boss->debug(1);
1220.Ve
1221.PP
1222.Vb 1
1223\& my $boss = Boss->new();
1224.Ve
1225.PP
1226.Vb 4
1227\& $boss->fullname->title("Don");
1228\& $boss->fullname->surname("Pichon Alvarez");
1229\& $boss->fullname->christian("Federico Jesus");
1230\& $boss->fullname->nickname("Fred");
1231.Ve
1232.PP
1233.Vb 2
1234\& $boss->age(47);
1235\& $boss->peers("Frank", "Felipe", "Faust");
1236.Ve
1237.PP
1238.Vb 2
1239\& printf "%s is age %d.\en", $boss->fullname->as_string, $boss->age;
1240\& printf "His peers are: %s\en", join(", ", $boss->peers);
1241.Ve
1242.PP
1243Running it, we see that we're still ok. If you'd like to dump out your
1244object in a nice format, somewhat like the way the 'x' command works in
1245the debugger, you could use the Data::Dumper module from \s-1CPAN\s0 this way:
1246.PP
1247.Vb 3
1248\& use Data::Dumper;
1249\& print "Here's the boss:\en";
1250\& print Dumper($boss);
1251.Ve
1252.PP
1253Which shows us something like this:
1254.PP
1255.Vb 16
1256\& Here's the boss:
1257\& $VAR1 = bless( {
1258\& _CENSUS => \e1,
1259\& FULLNAME => bless( {
1260\& TITLE => 'Don',
1261\& SURNAME => 'Pichon Alvarez',
1262\& NICK => 'Fred',
1263\& CHRISTIAN => 'Federico Jesus'
1264\& }, 'Fullname' ),
1265\& AGE => 47,
1266\& PEERS => [
1267\& 'Frank',
1268\& 'Felipe',
1269\& 'Faust'
1270\& ]
1271\& }, 'Boss' );
1272.Ve
1273.PP
1274Hm.... something's missing there. What about the salary, start date,
1275and \s-1ID\s0 fields? Well, we never set them to anything, even undef, so they
1276don't show up in the hash's keys. The Employee class has no \fInew()\fR method
1277of its own, and the \fInew()\fR method in Person doesn't know about Employees.
1278(Nor should it: proper \s-1OO\s0 design dictates that a subclass be allowed to
1279know about its immediate superclass, but never vice\-versa.) So let's
1280fix up \fIEmployee::new()\fR this way:
1281.PP
1282.Vb 9
1283\& sub new {
1284\& my $class = shift;
1285\& my $self = $class->SUPER::new();
1286\& $self->{SALARY} = undef;
1287\& $self->{ID} = undef;
1288\& $self->{START_DATE} = undef;
1289\& bless ($self, $class); # reconsecrate
1290\& return $self;
1291\& }
1292.Ve
1293.PP
1294Now if you dump out an Employee or Boss object, you'll find
1295that new fields show up there now.
1296.Sh "Multiple Inheritance"
1297.IX Subsection "Multiple Inheritance"
1298Ok, at the risk of confusing beginners and annoying \s-1OO\s0 gurus, it's
1299time to confess that Perl's object system includes that controversial
1300notion known as multiple inheritance, or \s-1MI\s0 for short. All this means
1301is that rather than having just one parent class who in turn might
1302itself have a parent class, etc., that you can directly inherit from
1303two or more parents. It's true that some uses of \s-1MI\s0 can get you into
1304trouble, although hopefully not quite so much trouble with Perl as with
1305dubiously-OO languages like \*(C+.
1306.PP
1307The way it works is actually pretty simple: just put more than one package
1308name in your \f(CW@ISA\fR array. When it comes time for Perl to go finding
1309methods for your object, it looks at each of these packages in order.
1310Well, kinda. It's actually a fully recursive, depth-first order.
1311Consider a bunch of \f(CW@ISA\fR arrays like this:
1312.PP
1313.Vb 3
1314\& @First::ISA = qw( Alpha );
1315\& @Second::ISA = qw( Beta );
1316\& @Third::ISA = qw( First Second );
1317.Ve
1318.PP
1319If you have an object of class Third:
1320.PP
1321.Vb 2
1322\& my $ob = Third->new();
1323\& $ob->spin();
1324.Ve
1325.PP
1326How do we find a \fIspin()\fR method (or a \fInew()\fR method for that matter)?
1327Because the search is depth\-first, classes will be looked up
1328in the following order: Third, First, Alpha, Second, and Beta.
1329.PP
1330In practice, few class modules have been seen that actually
1331make use of \s-1MI\s0. One nearly always chooses simple containership of
1332one class within another over \s-1MI\s0. That's why our Person
1333object \fIcontained\fR a Fullname object. That doesn't mean
1334it \fIwas\fR one.
1335.PP
1336However, there is one particular area where \s-1MI\s0 in Perl is rampant:
1337borrowing another class's class methods. This is rather common,
1338especially with some bundled \*(L"objectless\*(R" classes,
1339like Exporter, DynaLoader, AutoLoader, and SelfLoader. These classes
1340do not provide constructors; they exist only so you may inherit their
1341class methods. (It's not entirely clear why inheritance was done
1342here rather than traditional module importation.)
1343.PP
1344For example, here is the \s-1POSIX\s0 module's \f(CW@ISA:\fR
1345.PP
1346.Vb 2
1347\& package POSIX;
1348\& @ISA = qw(Exporter DynaLoader);
1349.Ve
1350.PP
1351The \s-1POSIX\s0 module isn't really an object module, but then,
1352neither are Exporter or DynaLoader. They're just lending their
1353classes' behaviours to \s-1POSIX\s0.
1354.PP
1355Why don't people use \s-1MI\s0 for object methods much? One reason is that
1356it can have complicated side\-effects. For one thing, your inheritance
1357graph (no longer a tree) might converge back to the same base class.
1358Although Perl guards against recursive inheritance, merely having parents
1359who are related to each other via a common ancestor, incestuous though
1360it sounds, is not forbidden. What if in our Third class shown above we
1361wanted its \fInew()\fR method to also call both overridden constructors in its
1362two parent classes? The \s-1SUPER\s0 notation would only find the first one.
1363Also, what about if the Alpha and Beta classes both had a common ancestor,
1364like Nought? If you kept climbing up the inheritance tree calling
1365overridden methods, you'd end up calling \fINought::new()\fR twice,
1366which might well be a bad idea.
1367.Sh "\s-1UNIVERSAL:\s0 The Root of All Objects"
1368.IX Subsection "UNIVERSAL: The Root of All Objects"
1369Wouldn't it be convenient if all objects were rooted at some ultimate
1370base class? That way you could give every object common methods without
1371having to go and add it to each and every \f(CW@ISA\fR. Well, it turns out that
1372you can. You don't see it, but Perl tacitly and irrevocably assumes
1373that there's an extra element at the end of \f(CW@ISA:\fR the class \s-1UNIVERSAL\s0.
1374In version 5.003, there were no predefined methods there, but you could put
1375whatever you felt like into it.
1376.PP
1377However, as of version 5.004 (or some subversive releases, like 5.003_08),
1378\&\s-1UNIVERSAL\s0 has some methods in it already. These are builtin to your Perl
1379binary, so they don't take any extra time to load. Predefined methods
1380include \fIisa()\fR, \fIcan()\fR, and \s-1\fIVERSION\s0()\fR. \fIisa()\fR tells you whether an object or
1381class \*(L"is\*(R" another one without having to traverse the hierarchy yourself:
1382.PP
1383.Vb 2
1384\& $has_io = $fd->isa("IO::Handle");
1385\& $itza_handle = IO::Socket->isa("IO::Handle");
1386.Ve
1387.PP
1388The \fIcan()\fR method, called against that object or class, reports back
1389whether its string argument is a callable method name in that class.
1390In fact, it gives you back a function reference to that method:
1391.PP
1392.Vb 1
1393\& $his_print_method = $obj->can('as_string');
1394.Ve
1395.PP
1396Finally, the \s-1VERSION\s0 method checks whether the class (or the object's
1397class) has a package global called \f(CW$VERSION\fR that's high enough, as in:
1398.PP
1399.Vb 2
1400\& Some_Module->VERSION(3.0);
1401\& $his_vers = $ob->VERSION();
1402.Ve
1403.PP
1404However, we don't usually call \s-1VERSION\s0 ourselves. (Remember that an all
1405uppercase function name is a Perl convention that indicates that the
1406function will be automatically used by Perl in some way.) In this case,
1407it happens when you say
1408.PP
1409.Vb 1
1410\& use Some_Module 3.0;
1411.Ve
1412.PP
1413If you wanted to add version checking to your Person class explained
1414above, just add this to Person.pm:
1415.PP
1416.Vb 1
1417\& our $VERSION = '1.1';
1418.Ve
1419.PP
1420and then in Employee.pm you can say
1421.PP
1422.Vb 1
1423\& use Person 1.1;
1424.Ve
1425.PP
1426And it would make sure that you have at least that version number or
1427higher available. This is not the same as loading in that exact version
1428number. No mechanism currently exists for concurrent installation of
1429multiple versions of a module. Lamentably.
1430.SH "Alternate Object Representations"
1431.IX Header "Alternate Object Representations"
1432Nothing requires objects to be implemented as hash references. An object
1433can be any sort of reference so long as its referent has been suitably
1434blessed. That means scalar, array, and code references are also fair
1435game.
1436.PP
1437A scalar would work if the object has only one datum to hold. An array
1438would work for most cases, but makes inheritance a bit dodgy because
1439you have to invent new indices for the derived classes.
1440.Sh "Arrays as Objects"
1441.IX Subsection "Arrays as Objects"
1442If the user of your class honors the contract and sticks to the advertised
1443interface, then you can change its underlying interface if you feel
1444like it. Here's another implementation that conforms to the same
1445interface specification. This time we'll use an array reference
1446instead of a hash reference to represent the object.
1447.PP
1448.Vb 2
1449\& package Person;
1450\& use strict;
1451.Ve
1452.PP
1453.Vb 1
1454\& my($NAME, $AGE, $PEERS) = ( 0 .. 2 );
1455.Ve
1456.PP
1457.Vb 11
1458\& ############################################
1459\& ## the object constructor (array version) ##
1460\& ############################################
1461\& sub new {
1462\& my $self = [];
1463\& $self->[$NAME] = undef; # this is unnecessary
1464\& $self->[$AGE] = undef; # as is this
1465\& $self->[$PEERS] = []; # but this isn't, really
1466\& bless($self);
1467\& return $self;
1468\& }
1469.Ve
1470.PP
1471.Vb 5
1472\& sub name {
1473\& my $self = shift;
1474\& if (@_) { $self->[$NAME] = shift }
1475\& return $self->[$NAME];
1476\& }
1477.Ve
1478.PP
1479.Vb 5
1480\& sub age {
1481\& my $self = shift;
1482\& if (@_) { $self->[$AGE] = shift }
1483\& return $self->[$AGE];
1484\& }
1485.Ve
1486.PP
1487.Vb 5
1488\& sub peers {
1489\& my $self = shift;
1490\& if (@_) { @{ $self->[$PEERS] } = @_ }
1491\& return @{ $self->[$PEERS] };
1492\& }
1493.Ve
1494.PP
1495.Vb 1
1496\& 1; # so the require or use succeeds
1497.Ve
1498.PP
1499You might guess that the array access would be a lot faster than the
1500hash access, but they're actually comparable. The array is a \fIlittle\fR
1501bit faster, but not more than ten or fifteen percent, even when you
1502replace the variables above like \f(CW$AGE\fR with literal numbers, like 1.
1503A bigger difference between the two approaches can be found in memory use.
1504A hash representation takes up more memory than an array representation
1505because you have to allocate memory for the keys as well as for the values.
1506However, it really isn't that bad, especially since as of version 5.004,
1507memory is only allocated once for a given hash key, no matter how many
1508hashes have that key. It's expected that sometime in the future, even
1509these differences will fade into obscurity as more efficient underlying
1510representations are devised.
1511.PP
1512Still, the tiny edge in speed (and somewhat larger one in memory)
1513is enough to make some programmers choose an array representation
1514for simple classes. There's still a little problem with
1515scalability, though, because later in life when you feel
1516like creating subclasses, you'll find that hashes just work
1517out better.
1518.Sh "Closures as Objects"
1519.IX Subsection "Closures as Objects"
1520Using a code reference to represent an object offers some fascinating
1521possibilities. We can create a new anonymous function (closure) who
1522alone in all the world can see the object's data. This is because we
1523put the data into an anonymous hash that's lexically visible only to
1524the closure we create, bless, and return as the object. This object's
1525methods turn around and call the closure as a regular subroutine call,
1526passing it the field we want to affect. (Yes,
1527the double-function call is slow, but if you wanted fast, you wouldn't
1528be using objects at all, eh? :\-)
1529.PP
1530Use would be similar to before:
1531.PP
1532.Vb 7
1533\& use Person;
1534\& $him = Person->new();
1535\& $him->name("Jason");
1536\& $him->age(23);
1537\& $him->peers( [ "Norbert", "Rhys", "Phineas" ] );
1538\& printf "%s is %d years old.\en", $him->name, $him->age;
1539\& print "His peers are: ", join(", ", @{$him->peers}), "\en";
1540.Ve
1541.PP
1542but the implementation would be radically, perhaps even sublimely
1543different:
1544.PP
1545.Vb 1
1546\& package Person;
1547.Ve
1548.PP
1549.Vb 15
1550\& sub new {
1551\& my $class = shift;
1552\& my $self = {
1553\& NAME => undef,
1554\& AGE => undef,
1555\& PEERS => [],
1556\& };
1557\& my $closure = sub {
1558\& my $field = shift;
1559\& if (@_) { $self->{$field} = shift }
1560\& return $self->{$field};
1561\& };
1562\& bless($closure, $class);
1563\& return $closure;
1564\& }
1565.Ve
1566.PP
1567.Vb 3
1568\& sub name { &{ $_[0] }("NAME", @_[ 1 .. $#_ ] ) }
1569\& sub age { &{ $_[0] }("AGE", @_[ 1 .. $#_ ] ) }
1570\& sub peers { &{ $_[0] }("PEERS", @_[ 1 .. $#_ ] ) }
1571.Ve
1572.PP
1573.Vb 1
1574\& 1;
1575.Ve
1576.PP
1577Because this object is hidden behind a code reference, it's probably a bit
1578mysterious to those whose background is more firmly rooted in standard
1579procedural or object-based programming languages than in functional
1580programming languages whence closures derive. The object
1581created and returned by the \fInew()\fR method is itself not a data reference
1582as we've seen before. It's an anonymous code reference that has within
1583it access to a specific version (lexical binding and instantiation)
1584of the object's data, which are stored in the private variable \f(CW$self\fR.
1585Although this is the same function each time, it contains a different
1586version of \f(CW$self\fR.
1587.PP
1588When a method like \f(CW\*(C`$him\->name("Jason")\*(C'\fR is called, its implicit
1589zeroth argument is the invoking object\*(--just as it is with all method
1590calls. But in this case, it's our code reference (something like a
1591function pointer in \*(C+, but with deep binding of lexical variables).
1592There's not a lot to be done with a code reference beyond calling it, so
1593that's just what we do when we say \f(CW\*(C`&{$_[0]}\*(C'\fR. This is just a regular
1594function call, not a method call. The initial argument is the string
1595\&\*(L"\s-1NAME\s0\*(R", and any remaining arguments are whatever had been passed to the
1596method itself.
1597.PP
1598Once we're executing inside the closure that had been created in \fInew()\fR,
1599the \f(CW$self\fR hash reference suddenly becomes visible. The closure grabs
1600its first argument (\*(L"\s-1NAME\s0\*(R" in this case because that's what the \fIname()\fR
1601method passed it), and uses that string to subscript into the private
1602hash hidden in its unique version of \f(CW$self\fR.
1603.PP
1604Nothing under the sun will allow anyone outside the executing method to
1605be able to get at this hidden data. Well, nearly nothing. You \fIcould\fR
1606single step through the program using the debugger and find out the
1607pieces while you're in the method, but everyone else is out of luck.
1608.PP
1609There, if that doesn't excite the Scheme folks, then I just don't know
1610what will. Translation of this technique into \*(C+, Java, or any other
1611braindead-static language is left as a futile exercise for aficionados
1612of those camps.
1613.PP
1614You could even add a bit of nosiness via the \fIcaller()\fR function and
1615make the closure refuse to operate unless called via its own package.
1616This would no doubt satisfy certain fastidious concerns of programming
1617police and related puritans.
1618.PP
1619If you were wondering when Hubris, the third principle virtue of a
1620programmer, would come into play, here you have it. (More seriously,
1621Hubris is just the pride in craftsmanship that comes from having written
1622a sound bit of well-designed code.)
1623.SH "AUTOLOAD: Proxy Methods"
1624.IX Header "AUTOLOAD: Proxy Methods"
1625Autoloading is a way to intercept calls to undefined methods. An autoload
1626routine may choose to create a new function on the fly, either loaded
1627from disk or perhaps just \fIeval()\fRed right there. This define-on-the-fly
1628strategy is why it's called autoloading.
1629.PP
1630But that's only one possible approach. Another one is to just
1631have the autoloaded method itself directly provide the
1632requested service. When used in this way, you may think
1633of autoloaded methods as \*(L"proxy\*(R" methods.
1634.PP
1635When Perl tries to call an undefined function in a particular package
1636and that function is not defined, it looks for a function in
1637that same package called \s-1AUTOLOAD\s0. If one exists, it's called
1638with the same arguments as the original function would have had.
1639The fully-qualified name of the function is stored in that package's
1640global variable \f(CW$AUTOLOAD\fR. Once called, the function can do anything
1641it would like, including defining a new function by the right name, and
1642then doing a really fancy kind of \f(CW\*(C`goto\*(C'\fR right to it, erasing itself
1643from the call stack.
1644.PP
1645What does this have to do with objects? After all, we keep talking about
1646functions, not methods. Well, since a method is just a function with
1647an extra argument and some fancier semantics about where it's found,
1648we can use autoloading for methods, too. Perl doesn't start looking
1649for an \s-1AUTOLOAD\s0 method until it has exhausted the recursive hunt up
1650through \f(CW@ISA\fR, though. Some programmers have even been known to define
1651a \s-1UNIVERSAL::AUTOLOAD\s0 method to trap unresolved method calls to any
1652kind of object.
1653.Sh "Autoloaded Data Methods"
1654.IX Subsection "Autoloaded Data Methods"
1655You probably began to get a little suspicious about the duplicated
1656code way back earlier when we first showed you the Person class, and
1657then later the Employee class. Each method used to access the
1658hash fields looked virtually identical. This should have tickled
1659that great programming virtue, Impatience, but for the time,
1660we let Laziness win out, and so did nothing. Proxy methods can cure
1661this.
1662.PP
1663Instead of writing a new function every time we want a new data field,
1664we'll use the autoload mechanism to generate (actually, mimic) methods on
1665the fly. To verify that we're accessing a valid member, we will check
1666against an \f(CW\*(C`_permitted\*(C'\fR (pronounced \*(L"under\-permitted\*(R") field, which
1667is a reference to a file-scoped lexical (like a C file static) hash of permitted fields in this record
1668called \f(CW%fields\fR. Why the underscore? For the same reason as the _CENSUS
1669field we once used: as a marker that means \*(L"for internal use only\*(R".
1670.PP
1671Here's what the module initialization code and class
1672constructor will look like when taking this approach:
1673.PP
1674.Vb 3
1675\& package Person;
1676\& use Carp;
1677\& our $AUTOLOAD; # it's a package global
1678.Ve
1679.PP
1680.Vb 5
1681\& my %fields = (
1682\& name => undef,
1683\& age => undef,
1684\& peers => undef,
1685\& );
1686.Ve
1687.PP
1688.Vb 9
1689\& sub new {
1690\& my $class = shift;
1691\& my $self = {
1692\& _permitted => \e%fields,
1693\& %fields,
1694\& };
1695\& bless $self, $class;
1696\& return $self;
1697\& }
1698.Ve
1699.PP
1700If we wanted our record to have default values, we could fill those in
1701where current we have \f(CW\*(C`undef\*(C'\fR in the \f(CW%fields\fR hash.
1702.PP
1703Notice how we saved a reference to our class data on the object itself?
1704Remember that it's important to access class data through the object
1705itself instead of having any method reference \f(CW%fields\fR directly, or else
1706you won't have a decent inheritance.
1707.PP
1708The real magic, though, is going to reside in our proxy method, which
1709will handle all calls to undefined methods for objects of class Person
1710(or subclasses of Person). It has to be called \s-1AUTOLOAD\s0. Again, it's
1711all caps because it's called for us implicitly by Perl itself, not by
1712a user directly.
1713.PP
1714.Vb 4
1715\& sub AUTOLOAD {
1716\& my $self = shift;
1717\& my $type = ref($self)
1718\& or croak "$self is not an object";
1719.Ve
1720.PP
1721.Vb 2
1722\& my $name = $AUTOLOAD;
1723\& $name =~ s/.*://; # strip fully-qualified portion
1724.Ve
1725.PP
1726.Vb 3
1727\& unless (exists $self->{_permitted}->{$name} ) {
1728\& croak "Can't access `$name' field in class $type";
1729\& }
1730.Ve
1731.PP
1732.Vb 6
1733\& if (@_) {
1734\& return $self->{$name} = shift;
1735\& } else {
1736\& return $self->{$name};
1737\& }
1738\& }
1739.Ve
1740.PP
1741Pretty nifty, eh? All we have to do to add new data fields
1742is modify \f(CW%fields\fR. No new functions need be written.
1743.PP
1744I could have avoided the \f(CW\*(C`_permitted\*(C'\fR field entirely, but I
1745wanted to demonstrate how to store a reference to class data on the
1746object so you wouldn't have to access that class data
1747directly from an object method.
1748.Sh "Inherited Autoloaded Data Methods"
1749.IX Subsection "Inherited Autoloaded Data Methods"
1750But what about inheritance? Can we define our Employee
1751class similarly? Yes, so long as we're careful enough.
1752.PP
1753Here's how to be careful:
1754.PP
1755.Vb 4
1756\& package Employee;
1757\& use Person;
1758\& use strict;
1759\& our @ISA = qw(Person);
1760.Ve
1761.PP
1762.Vb 4
1763\& my %fields = (
1764\& id => undef,
1765\& salary => undef,
1766\& );
1767.Ve
1768.PP
1769.Vb 10
1770\& sub new {
1771\& my $class = shift;
1772\& my $self = $class->SUPER::new();
1773\& my($element);
1774\& foreach $element (keys %fields) {
1775\& $self->{_permitted}->{$element} = $fields{$element};
1776\& }
1777\& @{$self}{keys %fields} = values %fields;
1778\& return $self;
1779\& }
1780.Ve
1781.PP
1782Once we've done this, we don't even need to have an
1783\&\s-1AUTOLOAD\s0 function in the Employee package, because
1784we'll grab Person's version of that via inheritance,
1785and it will all work out just fine.
1786.SH "Metaclassical Tools"
1787.IX Header "Metaclassical Tools"
1788Even though proxy methods can provide a more convenient approach to making
1789more struct-like classes than tediously coding up data methods as
1790functions, it still leaves a bit to be desired. For one thing, it means
1791you have to handle bogus calls that you don't mean to trap via your proxy.
1792It also means you have to be quite careful when dealing with inheritance,
1793as detailed above.
1794.PP
1795Perl programmers have responded to this by creating several different
1796class construction classes. These metaclasses are classes
1797that create other classes. A couple worth looking at are
1798Class::Struct and Alias. These and other related metaclasses can be
1799found in the modules directory on \s-1CPAN\s0.
1800.Sh "Class::Struct"
1801.IX Subsection "Class::Struct"
1802One of the older ones is Class::Struct. In fact, its syntax and
1803interface were sketched out long before perl5 even solidified into a
1804real thing. What it does is provide you a way to \*(L"declare\*(R" a class
1805as having objects whose fields are of a specific type. The function
1806that does this is called, not surprisingly enough, \fIstruct()\fR. Because
1807structures or records are not base types in Perl, each time you want to
1808create a class to provide a record-like data object, you yourself have
1809to define a \fInew()\fR method, plus separate data-access methods for each of
1810that record's fields. You'll quickly become bored with this process.
1811The \fIClass::Struct::struct()\fR function alleviates this tedium.
1812.PP
1813Here's a simple example of using it:
1814.PP
1815.Vb 2
1816\& use Class::Struct qw(struct);
1817\& use Jobbie; # user-defined; see below
1818.Ve
1819.PP
1820.Vb 5
1821\& struct 'Fred' => {
1822\& one => '$',
1823\& many => '@',
1824\& profession => 'Jobbie', # does not call Jobbie->new()
1825\& };
1826.Ve
1827.PP
1828.Vb 2
1829\& $ob = Fred->new(profession => Jobbie->new());
1830\& $ob->one("hmmmm");
1831.Ve
1832.PP
1833.Vb 4
1834\& $ob->many(0, "here");
1835\& $ob->many(1, "you");
1836\& $ob->many(2, "go");
1837\& print "Just set: ", $ob->many(2), "\en";
1838.Ve
1839.PP
1840.Vb 1
1841\& $ob->profession->salary(10_000);
1842.Ve
1843.PP
1844You can declare types in the struct to be basic Perl types, or
1845user-defined types (classes). User types will be initialized by calling
1846that class's \fInew()\fR method.
1847.PP
1848Take care that the \f(CW\*(C`Jobbie\*(C'\fR object is not created automatically by the
1849\&\f(CW\*(C`Fred\*(C'\fR class's \fInew()\fR method, so you should specify a \f(CW\*(C`Jobbie\*(C'\fR object
1850when you create an instance of \f(CW\*(C`Fred\*(C'\fR.
1851.PP
1852Here's a real-world example of using struct generation. Let's say you
1853wanted to override Perl's idea of \fIgethostbyname()\fR and \fIgethostbyaddr()\fR so
1854that they would return objects that acted like C structures. We don't
1855care about high\-falutin' \s-1OO\s0 gunk. All we want is for these objects to
1856act like structs in the C sense.
1857.PP
1858.Vb 5
1859\& use Socket;
1860\& use Net::hostent;
1861\& $h = gethostbyname("perl.com"); # object return
1862\& printf "perl.com's real name is %s, address %s\en",
1863\& $h->name, inet_ntoa($h->addr);
1864.Ve
1865.PP
1866Here's how to do this using the Class::Struct module.
1867The crux is going to be this call:
1868.PP
1869.Vb 7
1870\& struct 'Net::hostent' => [ # note bracket
1871\& name => '$',
1872\& aliases => '@',
1873\& addrtype => '$',
1874\& 'length' => '$',
1875\& addr_list => '@',
1876\& ];
1877.Ve
1878.PP
1879Which creates object methods of those names and types.
1880It even creates a \fInew()\fR method for us.
1881.PP
1882We could also have implemented our object this way:
1883.PP
1884.Vb 7
1885\& struct 'Net::hostent' => { # note brace
1886\& name => '$',
1887\& aliases => '@',
1888\& addrtype => '$',
1889\& 'length' => '$',
1890\& addr_list => '@',
1891\& };
1892.Ve
1893.PP
1894and then Class::Struct would have used an anonymous hash as the object
1895type, instead of an anonymous array. The array is faster and smaller,
1896but the hash works out better if you eventually want to do inheritance.
1897Since for this struct-like object we aren't planning on inheritance,
1898this time we'll opt for better speed and size over better flexibility.
1899.PP
1900Here's the whole implementation:
1901.PP
1902.Vb 2
1903\& package Net::hostent;
1904\& use strict;
1905.Ve
1906.PP
1907.Vb 11
1908\& BEGIN {
1909\& use Exporter ();
1910\& our @EXPORT = qw(gethostbyname gethostbyaddr gethost);
1911\& our @EXPORT_OK = qw(
1912\& $h_name @h_aliases
1913\& $h_addrtype $h_length
1914\& @h_addr_list $h_addr
1915\& );
1916\& our %EXPORT_TAGS = ( FIELDS => [ @EXPORT_OK, @EXPORT ] );
1917\& }
1918\& our @EXPORT_OK;
1919.Ve
1920.PP
1921.Vb 2
1922\& # Class::Struct forbids use of @ISA
1923\& sub import { goto &Exporter::import }
1924.Ve
1925.PP
1926.Vb 8
1927\& use Class::Struct qw(struct);
1928\& struct 'Net::hostent' => [
1929\& name => '$',
1930\& aliases => '@',
1931\& addrtype => '$',
1932\& 'length' => '$',
1933\& addr_list => '@',
1934\& ];
1935.Ve
1936.PP
1937.Vb 1
1938\& sub addr { shift->addr_list->[0] }
1939.Ve
1940.PP
1941.Vb 11
1942\& sub populate (@) {
1943\& return unless @_;
1944\& my $hob = new(); # Class::Struct made this!
1945\& $h_name = $hob->[0] = $_[0];
1946\& @h_aliases = @{ $hob->[1] } = split ' ', $_[1];
1947\& $h_addrtype = $hob->[2] = $_[2];
1948\& $h_length = $hob->[3] = $_[3];
1949\& $h_addr = $_[4];
1950\& @h_addr_list = @{ $hob->[4] } = @_[ (4 .. $#_) ];
1951\& return $hob;
1952\& }
1953.Ve
1954.PP
1955.Vb 1
1956\& sub gethostbyname ($) { populate(CORE::gethostbyname(shift)) }
1957.Ve
1958.PP
1959.Vb 7
1960\& sub gethostbyaddr ($;$) {
1961\& my ($addr, $addrtype);
1962\& $addr = shift;
1963\& require Socket unless @_;
1964\& $addrtype = @_ ? shift : Socket::AF_INET();
1965\& populate(CORE::gethostbyaddr($addr, $addrtype))
1966\& }
1967.Ve
1968.PP
1969.Vb 8
1970\& sub gethost($) {
1971\& if ($_[0] =~ /^\ed+(?:\e.\ed+(?:\e.\ed+(?:\e.\ed+)?)?)?$/) {
1972\& require Socket;
1973\& &gethostbyaddr(Socket::inet_aton(shift));
1974\& } else {
1975\& &gethostbyname;
1976\& }
1977\& }
1978.Ve
1979.PP
1980.Vb 1
1981\& 1;
1982.Ve
1983.PP
1984We've snuck in quite a fair bit of other concepts besides just dynamic
1985class creation, like overriding core functions, import/export bits,
1986function prototyping, short-cut function call via \f(CW&whatever\fR, and
1987function replacement with \f(CW\*(C`goto &whatever\*(C'\fR. These all mostly make
1988sense from the perspective of a traditional module, but as you can see,
1989we can also use them in an object module.
1990.PP
1991You can look at other object\-based, struct-like overrides of core
1992functions in the 5.004 release of Perl in File::stat, Net::hostent,
1993Net::netent, Net::protoent, Net::servent, Time::gmtime, Time::localtime,
1994User::grent, and User::pwent. These modules have a final component
1995that's all lowercase, by convention reserved for compiler pragmas,
1996because they affect the compilation and change a builtin function.
1997They also have the type names that a C programmer would most expect.
1998.Sh "Data Members as Variables"
1999.IX Subsection "Data Members as Variables"
2000If you're used to \*(C+ objects, then you're accustomed to being able to
2001get at an object's data members as simple variables from within a method.
2002The Alias module provides for this, as well as a good bit more, such
2003as the possibility of private methods that the object can call but folks
2004outside the class cannot.
2005.PP
2006Here's an example of creating a Person using the Alias module.
2007When you update these magical instance variables, you automatically
2008update value fields in the hash. Convenient, eh?
2009.PP
2010.Vb 1
2011\& package Person;
2012.Ve
2013.PP
2014.Vb 11
2015\& # this is the same as before...
2016\& sub new {
2017\& my $class = shift;
2018\& my $self = {
2019\& NAME => undef,
2020\& AGE => undef,
2021\& PEERS => [],
2022\& };
2023\& bless($self, $class);
2024\& return $self;
2025\& }
2026.Ve
2027.PP
2028.Vb 2
2029\& use Alias qw(attr);
2030\& our ($NAME, $AGE, $PEERS);
2031.Ve
2032.PP
2033.Vb 5
2034\& sub name {
2035\& my $self = attr shift;
2036\& if (@_) { $NAME = shift; }
2037\& return $NAME;
2038\& }
2039.Ve
2040.PP
2041.Vb 5
2042\& sub age {
2043\& my $self = attr shift;
2044\& if (@_) { $AGE = shift; }
2045\& return $AGE;
2046\& }
2047.Ve
2048.PP
2049.Vb 5
2050\& sub peers {
2051\& my $self = attr shift;
2052\& if (@_) { @PEERS = @_; }
2053\& return @PEERS;
2054\& }
2055.Ve
2056.PP
2057.Vb 5
2058\& sub exclaim {
2059\& my $self = attr shift;
2060\& return sprintf "Hi, I'm %s, age %d, working with %s",
2061\& $NAME, $AGE, join(", ", @PEERS);
2062\& }
2063.Ve
2064.PP
2065.Vb 4
2066\& sub happy_birthday {
2067\& my $self = attr shift;
2068\& return ++$AGE;
2069\& }
2070.Ve
2071.PP
2072The need for the \f(CW\*(C`our\*(C'\fR declaration is because what Alias does
2073is play with package globals with the same name as the fields. To use
2074globals while \f(CW\*(C`use strict\*(C'\fR is in effect, you have to predeclare them.
2075These package variables are localized to the block enclosing the \fIattr()\fR
2076call just as if you'd used a \fIlocal()\fR on them. However, that means that
2077they're still considered global variables with temporary values, just
2078as with any other \fIlocal()\fR.
2079.PP
2080It would be nice to combine Alias with
2081something like Class::Struct or Class::MethodMaker.
2082.SH "NOTES"
2083.IX Header "NOTES"
2084.Sh "Object Terminology"
2085.IX Subsection "Object Terminology"
2086In the various \s-1OO\s0 literature, it seems that a lot of different words
2087are used to describe only a few different concepts. If you're not
2088already an object programmer, then you don't need to worry about all
2089these fancy words. But if you are, then you might like to know how to
2090get at the same concepts in Perl.
2091.PP
2092For example, it's common to call an object an \fIinstance\fR of a class
2093and to call those objects' methods \fIinstance methods\fR. Data fields
2094peculiar to each object are often called \fIinstance data\fR or \fIobject
2095attributes\fR, and data fields common to all members of that class are
2096\&\fIclass data\fR, \fIclass attributes\fR, or \fIstatic data members\fR.
2097.PP
2098Also, \fIbase class\fR, \fIgeneric class\fR, and \fIsuperclass\fR all describe
2099the same notion, whereas \fIderived class\fR, \fIspecific class\fR, and
2100\&\fIsubclass\fR describe the other related one.
2101.PP
2102\&\*(C+ programmers have \fIstatic methods\fR and \fIvirtual methods\fR,
2103but Perl only has \fIclass methods\fR and \fIobject methods\fR.
2104Actually, Perl only has methods. Whether a method gets used
2105as a class or object method is by usage only. You could accidentally
2106call a class method (one expecting a string argument) on an
2107object (one expecting a reference), or vice versa.
2108.PP
2109From the \*(C+ perspective, all methods in Perl are virtual.
2110This, by the way, is why they are never checked for function
2111prototypes in the argument list as regular builtin and user-defined
2112functions can be.
2113.PP
2114Because a class is itself something of an object, Perl's classes can be
2115taken as describing both a \*(L"class as meta\-object\*(R" (also called \fIobject
2116factory\fR) philosophy and the \*(L"class as type definition\*(R" (\fIdeclaring\fR
2117behaviour, not \fIdefining\fR mechanism) idea. \*(C+ supports the latter
2118notion, but not the former.
2119.SH "SEE ALSO"
2120.IX Header "SEE ALSO"
2121The following manpages will doubtless provide more
2122background for this one:
2123perlmod,
2124perlref,
2125perlobj,
2126perlbot,
2127perltie,
2128and
2129overload.
2130.PP
2131perlboot is a kinder, gentler introduction to object-oriented
2132programming.
2133.PP
2134perltooc provides more detail on class data.
2135.PP
2136Some modules which might prove interesting are Class::Accessor,
2137Class::Class, Class::Contract, Class::Data::Inheritable,
2138Class::MethodMaker and Tie::SecureHash
2139.SH "AUTHOR AND COPYRIGHT"
2140.IX Header "AUTHOR AND COPYRIGHT"
2141Copyright (c) 1997, 1998 Tom Christiansen
2142All rights reserved.
2143.PP
2144This documentation is free; you can redistribute it and/or modify it
2145under the same terms as Perl itself.
2146.PP
2147Irrespective of its distribution, all code examples in this file
2148are hereby placed into the public domain. You are permitted and
2149encouraged to use this code in your own programs for fun
2150or for profit as you see fit. A simple comment in the code giving
2151credit would be courteous but is not required.
2152.SH "COPYRIGHT"
2153.IX Header "COPYRIGHT"
2154.Sh "Acknowledgments"
2155.IX Subsection "Acknowledgments"
2156Thanks to
2157Larry Wall,
2158Roderick Schertler,
2159Gurusamy Sarathy,
2160Dean Roehrich,
2161Raphael Manfredi,
2162Brent Halsey,
2163Greg Bacon,
2164Brad Appleton,
2165and many others for their helpful comments.