1HTML::Tree::AboutObjectUss(e3r)Contributed Perl DocumentHaTtMiLo:n:Tree::AboutObjects(3)
2
3
4
6 HTML::Tree::AboutObjects -- article: "User's View of Object-Oriented
7 Modules"
8
10 # This an article, not a module.
11
13 The following article by Sean M. Burke first appeared in The Perl Jour‐
14 nal #17 and is copyright 2000 The Perl Journal. It appears courtesy of
15 Jon Orwant and The Perl Journal. This document may be distributed
16 under the same terms as Perl itself.
17
19 -- Sean M. Burke
20
21 The first time that most Perl programmers run into object-oriented pro‐
22 gramming when they need to use a module whose interface is object-ori‐
23 ented. This is often a mystifying experience, since talk of "methods"
24 and "constructors" is unintelligible to programmers who thought that
25 functions and variables was all there was to worry about.
26
27 Articles and books that explain object-oriented programming (OOP), do
28 so in terms of how to program that way. That's understandable, and if
29 you learn to write object-oriented code of your own, you'd find it easy
30 to use object-oriented code that others write. But this approach is
31 the long way around for people whose immediate goal is just to use
32 existing object-oriented modules, but who don't yet want to know all
33 the gory details of having to write such modules for themselves.
34
35 This article is for those programmers -- programmers who want to know
36 about objects from the perspective of using object-oriented modules.
37
38 Modules and Their Functional Interfaces
39
40 Modules are the main way that Perl provides for bundling up code for
41 later use by yourself or others. As I'm sure you can't help noticing
42 from reading The Perl Journal, CPAN (the Comprehensive Perl Archive
43 Network) is the repository for modules (or groups of modules) that oth‐
44 ers have written, to do anything from composing music to accessing Web
45 pages. A good deal of those modules even come with every installation
46 of Perl.
47
48 One module that you may have used before, and which is fairly typical
49 in its interface, is Text::Wrap. It comes with Perl, so you don't even
50 need to install it from CPAN. You use it in a program of yours, by
51 having your program code say early on:
52
53 use Text::Wrap;
54
55 and after that, you can access a function called "wrap", which inserts
56 line-breaks in text that you feed it, so that the text will be wrapped
57 to seventy-two (or however many) columns.
58
59 The way this "use Text::Wrap" business works is that the module
60 Text::Wrap exists as a file "Text/Wrap.pm" somewhere in one of your
61 library directories. That file contains Perl code...
62
63 Footnote: And mixed in with the Perl code, there's documentation,
64 which is what you read with "perldoc Text::Wrap". The perldoc pro‐
65 gram simply ignores the code and formats the documentation text,
66 whereas "use Text::Wrap" loads and runs the code while ignoring the
67 documentation.
68
69 ...which, among other things, defines a function called
70 "Text::Wrap::wrap", and then "exports" that function, which means that
71 when you say "wrap" after having said "use Text::Wrap", you'll be actu‐
72 ally calling the "Text::Wrap::wrap" function. Some modules don't
73 export their functions, so you have to call them by their full name,
74 like "Text::Wrap::wrap(...parameters...)".
75
76 Regardless of whether the typical module exports the functions it pro‐
77 vides, a module is basically just a container for chunks of code that
78 do useful things. The way the module allows for you to interact with
79 it, is its interface. And when, like with Text::Wrap, its interface
80 consists of functions, the module is said to have a functional inter‐
81 face.
82
83 Footnote: the term "function" (and therefore "functional") has var‐
84 ious senses. I'm using the term here in its broadest sense, to
85 refer to routines -- bits of code that are called by some name and
86 which take parameters and return some value.
87
88 Using modules with functional interfaces is straightforward -- instead
89 of defining your own "wrap" function with "sub wrap { ... }", you
90 entrust "use Text::Wrap" to do that for you, along with whatever other
91 functions its defines and exports, according to the module's documenta‐
92 tion. Without too much bother, you can even write your own modules to
93 contain your frequently used functions; I suggest having a look at the
94 "perlmod" man page for more leads on doing this.
95
96 Modules with Object-Oriented Interfaces
97
98 So suppose that one day you want to write a program that will automate
99 the process of "ftp"ing a bunch of files from one server down to your
100 local machine, and then off to another server.
101
102 A quick browse through search.cpan.org turns up the module "Net::FTP",
103 which you can download and install it using normal installation
104 instructions (unless your sysadmin has already installed it, as many
105 have).
106
107 Like Text::Wrap or any other module with a familiarly functional inter‐
108 face, you start off using Net::FTP in your program by saying:
109
110 use Net::FTP;
111
112 However, that's where the similarity ends. The first hint of differ‐
113 ence is that the documentation for Net::FTP refers to it as a class. A
114 class is a kind of module, but one that has an object-oriented inter‐
115 face.
116
117 Whereas modules like Text::Wrap provide bits of useful code as func‐
118 tions, to be called like "function(...parameters...)" or like "Package‐
119 Name::function(...parameters...)", Net::FTP and other modules with
120 object-oriented interfaces provide methods. Methods are sort of like
121 functions in that they have a name and parameters; but methods look
122 different, and are different, because you have to call them with a syn‐
123 tax that has a class name or an object as a special argument. I'll
124 explain the syntax for method calls, and then later explain what they
125 all mean.
126
127 Some methods are meant to be called as class methods, with the class
128 name (same as the module name) as a special argument. Class methods
129 look like this:
130
131 ClassName->methodname(parameter1, parameter2, ...)
132 ClassName->methodname() # if no parameters
133 ClassName->methodname # same as above
134
135 which you will sometimes see written:
136
137 methodname ClassName (parameter1, parameter2, ...)
138 methodname ClassName # if no parameters
139
140 Basically all class methods are for making new objects, and methods
141 that make objects are called "constructors" (and the process of making
142 them is called "constructing" or "instantiating"). Constructor methods
143 typically have the name "new", or something including "new"
144 ("new_from_file", etc.); but they can conceivably be named anything --
145 DBI's constructor method is named "connect", for example.
146
147 The object that a constructor method returns is typically captured in a
148 scalar variable:
149
150 $object = ClassName->new(param1, param2...);
151
152 Once you have an object (more later on exactly what that is), you can
153 use the other kind of method call syntax, the syntax for object method
154 calls. Calling object methods is just like class methods, except that
155 instead of the ClassName as the special argument, you use an expression
156 that yeilds an "object". Usually this is just a scalar variable that
157 you earlier captured the output of the constructor in. Object method
158 calls look like this:
159
160 $object->methodname(parameter1, parameter2, ...);
161 $object->methodname() # if no parameters
162 $object->methodname # same as above
163
164 which is occasionally written as:
165
166 methodname $object (parameter1, parameter2, ...)
167 methodname $object # if no parameters
168
169 Examples of method calls are:
170
171 my $session1 = Net::FTP->new("ftp.myhost.com");
172 # Calls a class method "new", from class Net::FTP,
173 # with the single parameter "ftp.myhost.com",
174 # and saves the return value (which is, as usual,
175 # an object), in $session1.
176 # Could also be written:
177 # new Net::FTP('ftp.myhost.com')
178 $session1->login("sburke","aoeuaoeu")
179 ⎪⎪ die "failed to login!\n";
180 # calling the object method "login"
181 print "Dir:\n", $session1->dir(), "\n";
182 $session1->quit;
183 # same as $session1->quit()
184 print "Done\n";
185 exit;
186
187 Incidentally, I suggest always using the syntaxes with parentheses and
188 "->" in them,
189
190 Footnote: the character-pair "->" is supposed to look like an
191 arrow, not "negative greater-than"!
192
193 and avoiding the syntaxes that start out "methodname $object" or
194 "methodname ModuleName". When everything's going right, they all mean
195 the same thing as the "->" variants, but the syntax with "->" is more
196 visually distinct from function calls, as well as being immune to some
197 kinds of rare but puzzling ambiguities that can arise when you're try‐
198 ing to call methods that have the same name as subroutines you've
199 defined.
200
201 But, syntactic alternatives aside, all this talk of constructing
202 objects and object methods begs the question -- what is an object?
203 There are several angles to this question that the rest of this article
204 will answer in turn: what can you do with objects? what's in an
205 object? what's an object value? and why do some modules use objects
206 at all?
207
208 What Can You Do with Objects?
209
210 You've seen that you can make objects, and call object methods with
211 them. But what are object methods for? The answer depends on the
212 class:
213
214 A Net::FTP object represents a session between your computer and an FTP
215 server. So the methods you call on a Net::FTP object are for doing
216 whatever you'd need to do across an FTP connection. You make the ses‐
217 sion and log in:
218
219 my $session = Net::FTP->new('ftp.aol.com');
220 die "Couldn't connect!" unless defined $session;
221 # The class method call to "new" will return
222 # the new object if it goes OK, otherwise it
223 # will return undef.
224
225 $session->login('sburke', 'p@ssw3rD')
226 ⎪⎪ die "Did I change my password again?";
227 # The object method "login" will give a true
228 # return value if actually logs in, otherwise
229 # it'll return false.
230
231 You can use the session object to change directory on that session:
232
233 $session->cwd("/home/sburke/public_html")
234 ⎪⎪ die "Hey, that was REALLY supposed to work!";
235 # if the cwd fails, it'll return false
236
237 ...get files from the machine at the other end of the session...
238
239 foreach my $f ('log_report_ua.txt', 'log_report_dom.txt',
240 'log_report_browsers.txt')
241 {
242 $session->get($f) ⎪⎪ warn "Getting $f failed!"
243 };
244
245 ...and plenty else, ending finally with closing the connection:
246
247 $session->quit();
248
249 In short, object methods are for doing things related to (or with)
250 whatever the object represents. For FTP sessions, it's about sending
251 commands to the server at the other end of the connection, and that's
252 about it -- there, methods are for doing something to the world outside
253 the object, and the objects is just something that specifies what bit
254 of the world (well, what FTP session) to act upon.
255
256 With most other classes, however, the object itself stores some kind of
257 information, and it typically makes no sense to do things with such an
258 object without considering the data that's in the object.
259
260 What's in an Object?
261
262 An object is (with rare exceptions) a data structure containing a bunch
263 of attributes, each of which has a value, as well as a name that you
264 use when you read or set the attribute's value. Some of the object's
265 attributes are private, meaning you'll never see them documented
266 because they're not for you to read or write; but most of the object's
267 documented attributes are at least readable, and usually writeable, by
268 you. Net::FTP objects are a bit thin on attributes, so we'll use
269 objects from the class Business::US_Amort for this example. Busi‐
270 ness::US_Amort is a very simple class (available from CPAN) that I
271 wrote for making calculations to do with loans (specifically, amortiza‐
272 tion, using US-style algorithms).
273
274 An object of the class Business::US_Amort represents a loan with par‐
275 ticular parameters, i.e., attributes. The most basic attributes of a
276 "loan object" are its interest rate, its principal (how much money it's
277 for), and it's term (how long it'll take to repay). You need to set
278 these attributes before anything else can be done with the object. The
279 way to get at those attributes for loan objects is just like the way to
280 get at attributes for any class's objects: through accessors. An
281 accessor is simply any method that accesses (whether reading or writ‐
282 ing, AKA getting or putting) some attribute in the given object. More‐
283 over, accessors are the only way that you can change an object's
284 attributes. (If a module's documentation wants you to know about any
285 other way, it'll tell you.)
286
287 Usually, for simplicity's sake, an accessor is named after the
288 attribute it reads or writes. With Business::US_Amort objects, the
289 accessors you need to use first are "principal", "interest_rate", and
290 "term". Then, with at least those attributes set, you can call the
291 "run" method to figure out several things about the loan. Then you can
292 call various accessors, like "total_paid_toward_interest", to read the
293 results:
294
295 use Business::US_Amort;
296 my $loan = Business::US_Amort->new;
297 # Set the necessary attributes:
298 $loan->principal(123654);
299 $loan->interest_rate(9.25);
300 $loan->term(20); # twenty years
301
302 # NOW we know enough to calculate:
303 $loan->run;
304
305 # And see what came of that:
306 print
307 "Total paid toward interest: A WHOPPING ",
308 $loan->total_paid_interest, "!!\n";
309
310 This illustrates a convention that's common with accessors: calling the
311 accessor with no arguments (as with $loan->total_paid_interest) usually
312 means to read the value of that attribute, but providing a value (as
313 with $loan->term(20)) means you want that attribute to be set to that
314 value. This stands to reason: why would you be providing a value, if
315 not to set the attribute to that value?
316
317 Although a loan's term, principal, and interest rates are all single
318 numeric values, an objects values can any kind of scalar, or an array,
319 or even a hash. Moreover, an attribute's value(s) can be objects them‐
320 selves. For example, consider MIDI files (as I wrote about in TPJ#13):
321 a MIDI file usually consists of several tracks. A MIDI file is complex
322 enough to merit being an object with attributes like its overall tempo,
323 the file-format variant it's in, and the list of instrument tracks in
324 the file. But tracks themselves are complex enough to be objects too,
325 with attributes like their track-type, a list of MIDI commands if
326 they're a MIDI track, or raw data if they're not. So I ended up writ‐
327 ing the MIDI modules so that the "tracks" attribute of a MIDI::Opus
328 object is an array of objects from the class MIDI::Track. This may
329 seem like a runaround -- you ask what's in one object, and get another
330 object, or several! But in this case, it exactly reflects what the
331 module is for -- MIDI files contain MIDI tracks, which then contain
332 data.
333
334 What is an Object Value?
335
336 When you call a constructor like Net::FTP->new(hostname), you get back
337 an object value, a value you can later use, in combination with a
338 method name, to call object methods.
339
340 Now, so far we've been pretending, in the above examples, that the
341 variables $session or $loan are the objects you're dealing with. This
342 idea is innocuous up to a point, but it's really a misconception that
343 will, at best, limit you in what you know how to do. The reality is
344 not that the variables $session or $query are objects; it's a little
345 more indirect -- they hold values that symbolize objects. The kind of
346 value that $session or $query hold is what I'm calling an object value.
347
348 To understand what kind of value this is, first think about the other
349 kinds of scalar values you know about: The first two scalar values you
350 probably ever ran into in Perl are numbers and strings, which you
351 learned (or just assumed) will usually turn into each other on demand;
352 that is, the three-character string "2.5" can become the quantity two
353 and a half, and vice versa. Then, especially if you started using
354 "perl -w" early on, you learned about the undefined value, which can
355 turn into 0 if you treat it as a number, or the empty-string if you
356 treat it as a string.
357
358 Footnote: You may also have been learning about references, in
359 which case you're ready to hear that object values are just a kind
360 of reference, except that they reflect the class that created thing
361 they point to, instead of merely being a plain old array reference,
362 hash reference, etc. If this makes makes sense to you, and you
363 want to know more about how objects are implemented in Perl, have a
364 look at the "perltoot" man page.
365
366 And now you're learning about object values. An object value is a
367 value that points to a data structure somewhere in memory, which is
368 where all the attributes for this object are stored. That data struc‐
369 ture as a whole belongs to a class (probably the one you named in the
370 constructor method, like ClassName->new), so that the object value can
371 be used as part of object method calls.
372
373 If you want to actually see what an object value is, you might try just
374 saying "print $object". That'll get you something like this:
375
376 Net::FTP=GLOB(0x20154240)
377
378 or
379
380 Business::US_Amort=HASH(0x15424020)
381
382 That's not very helpful if you wanted to really get at the object's
383 insides, but that's because the object value is only a symbol for the
384 object. This may all sound very abstruse and metaphysical, so a real-
385 world allegory might be very helpful:
386
387 You get an advertisement in the mail saying that you have been
388 (im)personally selected to have the rare privilege of applying for
389 a credit card. For whatever reason, this offer sounds good to you,
390 so you fill out the form and mail it back to the credit card com‐
391 pany. They gleefully approve the application and create your
392 account, and send you a card with a number on it.
393
394 Now, you can do things with the number on that card -- clerks at
395 stores can ring up things you want to buy, and charge your account
396 by keying in the number on the card. You can pay for things you
397 order online by punching in the card number as part of your online
398 order. You can pay off part of the account by sending the credit
399 card people some of your money (well, a check) with some note (usu‐
400 ally the pre-printed slip) that has the card number for the account
401 you want to pay toward. And you should be able to call the credit
402 card company's computer and ask it things about the card, like its
403 balance, its credit limit, its APR, and maybe an itemization of
404 recent purchases ad payments.
405
406 Now, what you're really doing is manipulating a credit card
407 account, a completely abstract entity with some data attached to it
408 (balance, APR, etc). But for ease of access, you have a credit
409 card number that is a symbol for that account. Now, that symbol is
410 just a bunch of digits, and the number is effectively meaningless
411 and useless in and of itself -- but in the appropriate context,
412 it's understood to mean the credit card account you're accessing.
413
414 This is exactly the relationship between objects and object values, and
415 from this analogy, several facts about object values are a bit more
416 explicable:
417
418 * An object value does nothing in and of itself, but it's useful when
419 you use it in the context of an $object->method call, the same way that
420 a card number is useful in the context of some operation dealing with a
421 card account.
422
423 Moreover, several copies of the same object value all refer to the same
424 object, the same way that making several copies of your card number
425 won't change the fact that they all still refer to the same single
426 account (this is true whether you're "copying" the number by just writ‐
427 ing it down on different slips of paper, or whether you go to the trou‐
428 ble of forging exact replicas of your own plastic credit card). That's
429 why this:
430
431 $x = Net::FTP->new("ftp.aol.com");
432 $x->login("sburke", "aoeuaoeu");
433
434 does the same thing as this:
435
436 $x = Net::FTP->new("ftp.aol.com");
437 $y = $x;
438 $z = $y;
439 $z->login("sburke", "aoeuaoeu");
440
441 That is, $z and $y and $x are three different slots for values, but
442 what's in those slots are all object values pointing to the same object
443 -- you don't have three different FTP connections, just three variables
444 with values pointing to the some single FTP connection.
445
446 * You can't tell much of anything about the object just by looking at
447 the object value, any more than you can see your credit account balance
448 by holding the plastic card up to the light, or by adding up the digits
449 in your credit card number.
450
451 * You can't just make up your own object values and have them work --
452 they can come only from constructor methods of the appropriate class.
453 Similarly, you get a credit card number only by having a bank approve
454 your application for a credit card account -- at which point they let
455 you know what the number of your new card is.
456
457 Now, there's even more to the fact that you can't just make up your own
458 object value: even though you can print an object value and get a
459 string like "Net::FTP=GLOB(0x20154240)", that string is just a repre‐
460 sentation of an object value.
461
462 Internally, an object value has a basically different type from a
463 string, or a number, or the undefined value -- if $x holds a real
464 string, then that value's slot in memory says "this is a value of type
465 string, and its characters are...", whereas if it's an object value,
466 the value's slot in memory says, "this is a value of type reference,
467 and the location in memory that it points to is..." (and by looking at
468 what's at that location, Perl can tell the class of what's there).
469
470 Perl programmers typically don't have to think about all these details
471 of Perl's internals. Many other languages force you to be more con‐
472 scious of the differences between all of these (and also between types
473 of numbers, which are stored differently depending on their size and
474 whether they have fractional parts). But Perl does its best to hide
475 the different types of scalars from you -- it turns numbers into
476 strings and back as needed, and takes the string or number representa‐
477 tion of undef or of object values as needed. However, you can't go
478 from a string representation of an object value, back to an object
479 value. And that's why this doesn't work:
480
481 $x = Net::FTP->new('ftp.aol.com');
482 $y = Net::FTP->new('ftp.netcom.com');
483 $z = Net::FTP->new('ftp.qualcomm.com');
484 $all = join(' ', $x,$y,$z); # !!!
485 ...later...
486 ($aol, $netcom, $qualcomm) = split(' ', $all); # !!!
487 $aol->login("sburke", "aoeuaoeu");
488 $netcom->login("sburke", "qjkxqjkx");
489 $qualcomm->login("smb", "dhtndhtn");
490
491 This fails because $aol ends up holding merely the string representa‐
492 tion of the object value from $x, not the object value itself -- when
493 "join" tried to join the characters of the "strings" $x, $y, and $z,
494 Perl saw that they weren't strings at all, so it gave "join" their
495 string representations.
496
497 Unfortunately, this distinction between object values and their string
498 representations doesn't really fit into the analogy of credit card num‐
499 bers, because credit card numbers really are numbers -- even thought
500 they don't express any meaningful quantity, if you stored them in a
501 database as a quantity (as opposed to just an ASCII string), that
502 wouldn't stop them from being valid as credit card numbers.
503
504 This may seem rather academic, but there's there's two common mistakes
505 programmers new to objects often make, which make sense only in terms
506 of the distinction between object values and their string representa‐
507 tions:
508
509 The first common error involves forgetting (or never having known in
510 the first place) that when you go to use a value as a hash key, Perl
511 uses the string representation of that value. When you want to use the
512 numeric value two and a half as a key, Perl turns it into the three-
513 character string "2.5". But if you then want to use that string as a
514 number, Perl will treat it as meaning two and a half, so you're usually
515 none the wiser that Perl converted the number to a string and back.
516 But recall that Perl can't turn strings back into objects -- so if you
517 tried to use a Net::FTP object value as a hash key, Perl actually used
518 its string representation, like "Net::FTP=GLOB(0x20154240)", but that
519 string is unusable as an object value. (Incidentally, there's a module
520 Tie::RefHash that implements hashes that do let you use real object-
521 values as keys.)
522
523 The second common error with object values is in trying to save an
524 object value to disk (whether printing it to a file, or storing it in a
525 conventional database file). All you'll get is the string, which will
526 be useless.
527
528 When you want to save an object and restore it later, you may find that
529 the object's class already provides a method specifically for this.
530 For example, MIDI::Opus provides methods for writing an object to disk
531 as a standard MIDI file. The file can later be read back into memory
532 by a MIDI::Opus constructor method, which will return a new MIDI::Opus
533 object representing whatever file you tell it to read into memory.
534 Similar methods are available with, for example, classes that manipu‐
535 late graphic images and can save them to files, which can be read back
536 later.
537
538 But some classes, like Business::US_Amort, provide no such methods for
539 storing an object in a file. When this is the case, you can try using
540 any of the Data::Dumper, Storable, or FreezeThaw modules. Using these
541 will be unproblematic for objects of most classes, but it may run into
542 limitations with others. For example, a Business::US_Amort object can
543 be turned into a string with Data::Dumper, and that string written to a
544 file. When it's restored later, its attributes will be accessable as
545 normal. But in the unlikely case that the loan object was saved in
546 mid-calculation, the calculation may not be resumable. This is because
547 of the way that that particular class does its calculations, but simi‐
548 lar limitations may occur with objects from other classses.
549
550 But often, even wanting to save an object is basically wrong -- what
551 would saving an ftp session even mean? Saving the hostname, username,
552 and password? current directory on both machines? the local TCP/IP
553 port number? In the case of "saving" a Net::FTP object, you're better
554 off just saving whatever details you actually need for your own pur‐
555 poses, so that you can make a new object later and just set those val‐
556 ues for it.
557
558 So Why Do Some Modules Use Objects?
559
560 All these details of using objects are definitely enough to make you
561 wonder -- is it worth the bother? If you're a module author, writing
562 your module with an object-oriented interface restricts the audience of
563 potential users to those who understand the basic concepts of objects
564 and object values, as well as Perl's syntax for calling methods. Why
565 complicate things by having an object-oriented interface?
566
567 A somewhat esoteric answer is that a module has an object-oriented
568 interface because the module's insides are written in an object-ori‐
569 ented style. This article is about the basics of object-oriented
570 interfaces, and it'd be going far afield to explain what object-ori‐
571 ented design is. But the short story is that object-oriented design is
572 just one way of attacking messy problems. It's a way that many pro‐
573 grammers find very helpful (and which others happen to find to be far
574 more of a hassle than it's worth, incidentally), and it just happens to
575 show up for you, the module user, as merely the style of interface.
576
577 But a simpler answer is that a functional interface is sometimes a hin‐
578 drance, because it limits the number of things you can do at once --
579 limiting it, in fact, to one. For many problems that some modules are
580 meant to solve, doing without an object-oriented interface would be
581 like wishing that Perl didn't use filehandles. The ideas are rather
582 simpler -- just imagine that Perl let you access files, but only one at
583 a time, with code like:
584
585 open("foo.txt") ⎪⎪ die "Can't open foo.txt: $!";
586 while(readline) {
587 print $_ if /bar/;
588 }
589 close;
590
591 That hypothetical kind of Perl would be simpler, by doing without file‐
592 handles. But you'd be out of luck if you wanted to read from one file
593 while reading from another, or read from two and print to a third.
594
595 In the same way, a functional FTP module would be fine for just upload‐
596 ing files to one server at a time, but it wouldn't allow you to easily
597 write programs that make need to use several simultaneous sessions
598 (like "look at server A and server B, and if A has a file called X.dat,
599 then download it locally and then upload it to server B -- except if B
600 has a file called Y.dat, in which case do it the other way around").
601
602 Some kinds of problems that modules solve just lend themselves to an
603 object-oriented interface. For those kinds of tasks, a functional
604 interface would be more familiar, but less powerful. Learning to use
605 object-oriented modules' interfaces does require becoming comfortable
606 with the concepts from this article. But in the end it will allow you
607 to use a broader range of modules and, with them, to write programs
608 that can do more.
609
610 [end body of article]
611
612 [Author Credit]
613
614 Sean M. Burke has contributed several modules to CPAN, about half of
615 them object-oriented.
616
617 [The next section should be in a greybox:]
618
619 The Gory Details
620
621 For sake of clarity of explanation, I had to oversimplify some of the
622 facts about objects. Here's a few of the gorier details:
623
624 * Every example I gave of a constructor was a class method. But object
625 methods can be constructors, too, if the class was written to work that
626 way: $new = $old->copy, $node_y = $node_x->new_subnode, or the like.
627
628 * I've given the impression that there's two kinds of methods: object
629 methods and class methods. In fact, the same method can be both,
630 because it's not the kind of method it is, but the kind of calls it's
631 written to accept -- calls that pass an object, or calls that pass a
632 class-name.
633
634 * The term "object value" isn't something you'll find used much any‐
635 where else. It's just my shorthand for what would properly be called
636 an "object reference" or "reference to a blessed item". In fact, peo‐
637 ple usually say "object" when they properly mean a reference to that
638 object.
639
640 * I mentioned creating objects with constructors, but I didn't mention
641 destroying them with destructor -- a destructor is a kind of method
642 that you call to tidy up the object once you're done with it, and want
643 it to neatly go away (close connections, delete temporary files, free
644 up memory, etc). But because of the way Perl handles memory, most mod‐
645 ules won't require the user to know about destructors.
646
647 * I said that class method syntax has to have the class name, as in
648 $session = Net::FTP->new($host). Actually, you can instead use any
649 expression that returns a class name: $ftp_class = 'Net::FTP'; $session
650 = $ftp_class->new($host). Moreover, instead of the method name for
651 object- or class-method calls, you can use a scalar holding the method
652 name: $foo->$method($host). But, in practice, these syntaxes are
653 rarely useful.
654
655 And finally, to learn about objects from the perspective of writing
656 your own classes, see the "perltoot" documentation, or Damian Conway's
657 exhaustive and clear book Object Oriented Perl (Manning Publications
658 1999, ISBN 1-884777-79-1).
659
661 Return to the HTML::Tree docs.
662
663
664
665perl v5.8.8 2006-08-04 HTML::Tree::AboutObjects(3)