1HTML::Tree::AboutObjectUss(e3r)Contributed Perl DocumentHaTtMiLo:n:Tree::AboutObjects(3)
2
3
4

NAME

6       HTML::Tree::AboutObjects -- article: "User's View of Object-Oriented
7       Modules"
8

SYNOPSIS

10         # This an article, not a module.
11

DESCRIPTION

13       The following article by Sean M. Burke first appeared in The Perl
14       Journal #17 and is copyright 2000 The Perl Journal. It appears courtesy
15       of Jon Orwant and The Perl Journal.  This document may be distributed
16       under the same terms as Perl itself.
17

A User's View of Object-Oriented Modules

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

BACK

655       Return to the HTML::Tree docs.
656
657
658
659perl v5.34.0                      2022-01-21       HTML::Tree::AboutObjects(3)
Impressum