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