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