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