1PERLOBJ(1) Perl Programmers Reference Guide PERLOBJ(1)
2
3
4
6 perlobj - Perl object reference
7
9 This document provides a reference for Perl's object orientation
10 features. If you're looking for an introduction to object-oriented
11 programming in Perl, please see perlootut.
12
13 In order to understand Perl objects, you first need to understand
14 references in Perl. See perlref for details.
15
16 This document describes all of Perl's object-oriented (OO) features
17 from the ground up. If you're just looking to write some object-
18 oriented code of your own, you are probably better served by using one
19 of the object systems from CPAN described in perlootut.
20
21 If you're looking to write your own object system, or you need to
22 maintain code which implements objects from scratch then this document
23 will help you understand exactly how Perl does object orientation.
24
25 There are a few basic principles which define object oriented Perl:
26
27 1. An object is simply a data structure that knows to which class it
28 belongs.
29
30 2. A class is simply a package. A class provides methods that expect
31 to operate on objects.
32
33 3. A method is simply a subroutine that expects a reference to an
34 object (or a package name, for class methods) as the first
35 argument.
36
37 Let's look at each of these principles in depth.
38
39 An Object is Simply a Data Structure
40 Unlike many other languages which support object orientation, Perl does
41 not provide any special syntax for constructing an object. Objects are
42 merely Perl data structures (hashes, arrays, scalars, filehandles,
43 etc.) that have been explicitly associated with a particular class.
44
45 That explicit association is created by the built-in "bless" function,
46 which is typically used within the constructor subroutine of the class.
47
48 Here is a simple constructor:
49
50 package File;
51
52 sub new {
53 my $class = shift;
54
55 return bless {}, $class;
56 }
57
58 The name "new" isn't special. We could name our constructor something
59 else:
60
61 package File;
62
63 sub load {
64 my $class = shift;
65
66 return bless {}, $class;
67 }
68
69 The modern convention for OO modules is to always use "new" as the name
70 for the constructor, but there is no requirement to do so. Any
71 subroutine that blesses a data structure into a class is a valid
72 constructor in Perl.
73
74 In the previous examples, the "{}" code creates a reference to an empty
75 anonymous hash. The "bless" function then takes that reference and
76 associates the hash with the class in $class. In the simplest case, the
77 $class variable will end up containing the string "File".
78
79 We can also use a variable to store a reference to the data structure
80 that is being blessed as our object:
81
82 sub new {
83 my $class = shift;
84
85 my $self = {};
86 bless $self, $class;
87
88 return $self;
89 }
90
91 Once we've blessed the hash referred to by $self we can start calling
92 methods on it. This is useful if you want to put object initialization
93 in its own separate method:
94
95 sub new {
96 my $class = shift;
97
98 my $self = {};
99 bless $self, $class;
100
101 $self->_initialize();
102
103 return $self;
104 }
105
106 Since the object is also a hash, you can treat it as one, using it to
107 store data associated with the object. Typically, code inside the class
108 can treat the hash as an accessible data structure, while code outside
109 the class should always treat the object as opaque. This is called
110 encapsulation. Encapsulation means that the user of an object does not
111 have to know how it is implemented. The user simply calls documented
112 methods on the object.
113
114 Note, however, that (unlike most other OO languages) Perl does not
115 ensure or enforce encapsulation in any way. If you want objects to
116 actually be opaque you need to arrange for that yourself. This can be
117 done in a variety of ways, including using "Inside-Out objects" or
118 modules from CPAN.
119
120 Objects Are Blessed; Variables Are Not
121
122 When we bless something, we are not blessing the variable which
123 contains a reference to that thing, nor are we blessing the reference
124 that the variable stores; we are blessing the thing that the variable
125 refers to (sometimes known as the referent). This is best demonstrated
126 with this code:
127
128 use Scalar::Util 'blessed';
129
130 my $foo = {};
131 my $bar = $foo;
132
133 bless $foo, 'Class';
134 print blessed( $bar ) // 'not blessed'; # prints "Class"
135
136 $bar = "some other value";
137 print blessed( $bar ) // 'not blessed'; # prints "not blessed"
138
139 When we call "bless" on a variable, we are actually blessing the
140 underlying data structure that the variable refers to. We are not
141 blessing the reference itself, nor the variable that contains that
142 reference. That's why the second call to "blessed( $bar )" returns
143 false. At that point $bar is no longer storing a reference to an
144 object.
145
146 You will sometimes see older books or documentation mention "blessing a
147 reference" or describe an object as a "blessed reference", but this is
148 incorrect. It isn't the reference that is blessed as an object; it's
149 the thing the reference refers to (i.e. the referent).
150
151 A Class is Simply a Package
152 Perl does not provide any special syntax for class definitions. A
153 package is simply a namespace containing variables and subroutines. The
154 only difference is that in a class, the subroutines may expect a
155 reference to an object or the name of a class as the first argument.
156 This is purely a matter of convention, so a class may contain both
157 methods and subroutines which don't operate on an object or class.
158
159 Each package contains a special array called @ISA. The @ISA array
160 contains a list of that class's parent classes, if any. This array is
161 examined when Perl does method resolution, which we will cover later.
162
163 Calling methods from a package means it must be loaded, of course, so
164 you will often want to load a module and add it to @ISA at the same
165 time. You can do so in a single step using the parent pragma. (In
166 older code you may encounter the base pragma, which is nowadays
167 discouraged except when you have to work with the equally discouraged
168 fields pragma.)
169
170 However the parent classes are set, the package's @ISA variable will
171 contain a list of those parents. This is simply a list of scalars, each
172 of which is a string that corresponds to a package name.
173
174 All classes inherit from the UNIVERSAL class implicitly. The UNIVERSAL
175 class is implemented by the Perl core, and provides several default
176 methods, such as "isa()", "can()", and "VERSION()". The "UNIVERSAL"
177 class will never appear in a package's @ISA variable.
178
179 Perl only provides method inheritance as a built-in feature. Attribute
180 inheritance is left up the class to implement. See the "Writing
181 Accessors" section for details.
182
183 A Method is Simply a Subroutine
184 Perl does not provide any special syntax for defining a method. A
185 method is simply a regular subroutine, and is declared with "sub".
186 What makes a method special is that it expects to receive either an
187 object or a class name as its first argument.
188
189 Perl does provide special syntax for method invocation, the "->"
190 operator. We will cover this in more detail later.
191
192 Most methods you write will expect to operate on objects:
193
194 sub save {
195 my $self = shift;
196
197 open my $fh, '>', $self->path() or die $!;
198 print {$fh} $self->data() or die $!;
199 close $fh or die $!;
200 }
201
202 Method Invocation
203 Calling a method on an object is written as "$object->method".
204
205 The left hand side of the method invocation (or arrow) operator is the
206 object (or class name), and the right hand side is the method name.
207
208 my $pod = File->new( 'perlobj.pod', $data );
209 $pod->save();
210
211 The "->" syntax is also used when dereferencing a reference. It looks
212 like the same operator, but these are two different operations.
213
214 When you call a method, the thing on the left side of the arrow is
215 passed as the first argument to the method. That means when we call
216 "Critter->new()", the "new()" method receives the string "Critter" as
217 its first argument. When we call "$fred->speak()", the $fred variable
218 is passed as the first argument to "speak()".
219
220 Just as with any Perl subroutine, all of the arguments passed in @_ are
221 aliases to the original argument. This includes the object itself. If
222 you assign directly to $_[0] you will change the contents of the
223 variable that holds the reference to the object. We recommend that you
224 don't do this unless you know exactly what you're doing.
225
226 Perl knows what package the method is in by looking at the left side of
227 the arrow. If the left hand side is a package name, it looks for the
228 method in that package. If the left hand side is an object, then Perl
229 looks for the method in the package that the object has been blessed
230 into.
231
232 If the left hand side is neither a package name nor an object, then the
233 method call will cause an error, but see the section on "Method Call
234 Variations" for more nuances.
235
236 Inheritance
237 We already talked about the special @ISA array and the parent pragma.
238
239 When a class inherits from another class, any methods defined in the
240 parent class are available to the child class. If you attempt to call a
241 method on an object that isn't defined in its own class, Perl will also
242 look for that method in any parent classes it may have.
243
244 package File::MP3;
245 use parent 'File'; # sets @File::MP3::ISA = ('File');
246
247 my $mp3 = File::MP3->new( 'Andvari.mp3', $data );
248 $mp3->save();
249
250 Since we didn't define a "save()" method in the "File::MP3" class, Perl
251 will look at the "File::MP3" class's parent classes to find the
252 "save()" method. If Perl cannot find a "save()" method anywhere in the
253 inheritance hierarchy, it will die.
254
255 In this case, it finds a "save()" method in the "File" class. Note that
256 the object passed to "save()" in this case is still a "File::MP3"
257 object, even though the method is found in the "File" class.
258
259 We can override a parent's method in a child class. When we do so, we
260 can still call the parent class's method with the "SUPER" pseudo-class.
261
262 sub save {
263 my $self = shift;
264
265 say 'Prepare to rock';
266 $self->SUPER::save();
267 }
268
269 The "SUPER" modifier can only be used for method calls. You can't use
270 it for regular subroutine calls or class methods:
271
272 SUPER::save($thing); # FAIL: looks for save() sub in package SUPER
273
274 SUPER->save($thing); # FAIL: looks for save() method in class
275 # SUPER
276
277 $thing->SUPER::save(); # Okay: looks for save() method in parent
278 # classes
279
280 How SUPER is Resolved
281
282 The "SUPER" pseudo-class is resolved from the package where the call is
283 made. It is not resolved based on the object's class. This is
284 important, because it lets methods at different levels within a deep
285 inheritance hierarchy each correctly call their respective parent
286 methods.
287
288 package A;
289
290 sub new {
291 return bless {}, shift;
292 }
293
294 sub speak {
295 my $self = shift;
296
297 say 'A';
298 }
299
300 package B;
301
302 use parent -norequire, 'A';
303
304 sub speak {
305 my $self = shift;
306
307 $self->SUPER::speak();
308
309 say 'B';
310 }
311
312 package C;
313
314 use parent -norequire, 'B';
315
316 sub speak {
317 my $self = shift;
318
319 $self->SUPER::speak();
320
321 say 'C';
322 }
323
324 my $c = C->new();
325 $c->speak();
326
327 In this example, we will get the following output:
328
329 A
330 B
331 C
332
333 This demonstrates how "SUPER" is resolved. Even though the object is
334 blessed into the "C" class, the "speak()" method in the "B" class can
335 still call "SUPER::speak()" and expect it to correctly look in the
336 parent class of "B" (i.e the class the method call is in), not in the
337 parent class of "C" (i.e. the class the object belongs to).
338
339 There are rare cases where this package-based resolution can be a
340 problem. If you copy a subroutine from one package to another, "SUPER"
341 resolution will be done based on the original package.
342
343 Multiple Inheritance
344
345 Multiple inheritance often indicates a design problem, but Perl always
346 gives you enough rope to hang yourself with if you ask for it.
347
348 To declare multiple parents, you simply need to pass multiple class
349 names to "use parent":
350
351 package MultiChild;
352
353 use parent 'Parent1', 'Parent2';
354
355 Method Resolution Order
356
357 Method resolution order only matters in the case of multiple
358 inheritance. In the case of single inheritance, Perl simply looks up
359 the inheritance chain to find a method:
360
361 Grandparent
362 |
363 Parent
364 |
365 Child
366
367 If we call a method on a "Child" object and that method is not defined
368 in the "Child" class, Perl will look for that method in the "Parent"
369 class and then, if necessary, in the "Grandparent" class.
370
371 If Perl cannot find the method in any of these classes, it will die
372 with an error message.
373
374 When a class has multiple parents, the method lookup order becomes more
375 complicated.
376
377 By default, Perl does a depth-first left-to-right search for a method.
378 That means it starts with the first parent in the @ISA array, and then
379 searches all of its parents, grandparents, etc. If it fails to find the
380 method, it then goes to the next parent in the original class's @ISA
381 array and searches from there.
382
383 SharedGreatGrandParent
384 / \
385 PaternalGrandparent MaternalGrandparent
386 \ /
387 Father Mother
388 \ /
389 Child
390
391 So given the diagram above, Perl will search "Child", "Father",
392 "PaternalGrandparent", "SharedGreatGrandParent", "Mother", and finally
393 "MaternalGrandparent". This may be a problem because now we're looking
394 in "SharedGreatGrandParent" before we've checked all its derived
395 classes (i.e. before we tried "Mother" and "MaternalGrandparent").
396
397 It is possible to ask for a different method resolution order with the
398 mro pragma.
399
400 package Child;
401
402 use mro 'c3';
403 use parent 'Father', 'Mother';
404
405 This pragma lets you switch to the "C3" resolution order. In simple
406 terms, "C3" order ensures that shared parent classes are never searched
407 before child classes, so Perl will now search: "Child", "Father",
408 "PaternalGrandparent", "Mother" "MaternalGrandparent", and finally
409 "SharedGreatGrandParent". Note however that this is not "breadth-first"
410 searching: All the "Father" ancestors (except the common ancestor) are
411 searched before any of the "Mother" ancestors are considered.
412
413 The C3 order also lets you call methods in sibling classes with the
414 "next" pseudo-class. See the mro documentation for more details on this
415 feature.
416
417 Method Resolution Caching
418
419 When Perl searches for a method, it caches the lookup so that future
420 calls to the method do not need to search for it again. Changing a
421 class's parent class or adding subroutines to a class will invalidate
422 the cache for that class.
423
424 The mro pragma provides some functions for manipulating the method
425 cache directly.
426
427 Writing Constructors
428 As we mentioned earlier, Perl provides no special constructor syntax.
429 This means that a class must implement its own constructor. A
430 constructor is simply a class method that returns a reference to a new
431 object.
432
433 The constructor can also accept additional parameters that define the
434 object. Let's write a real constructor for the "File" class we used
435 earlier:
436
437 package File;
438
439 sub new {
440 my $class = shift;
441 my ( $path, $data ) = @_;
442
443 my $self = bless {
444 path => $path,
445 data => $data,
446 }, $class;
447
448 return $self;
449 }
450
451 As you can see, we've stored the path and file data in the object
452 itself. Remember, under the hood, this object is still just a hash.
453 Later, we'll write accessors to manipulate this data.
454
455 For our "File::MP3" class, we can check to make sure that the path
456 we're given ends with ".mp3":
457
458 package File::MP3;
459
460 sub new {
461 my $class = shift;
462 my ( $path, $data ) = @_;
463
464 die "You cannot create a File::MP3 without an mp3 extension\n"
465 unless $path =~ /\.mp3\z/;
466
467 return $class->SUPER::new(@_);
468 }
469
470 This constructor lets its parent class do the actual object
471 construction.
472
473 Attributes
474 An attribute is a piece of data belonging to a particular object.
475 Unlike most object-oriented languages, Perl provides no special syntax
476 or support for declaring and manipulating attributes.
477
478 Attributes are often stored in the object itself. For example, if the
479 object is an anonymous hash, we can store the attribute values in the
480 hash using the attribute name as the key.
481
482 While it's possible to refer directly to these hash keys outside of the
483 class, it's considered a best practice to wrap all access to the
484 attribute with accessor methods.
485
486 This has several advantages. Accessors make it easier to change the
487 implementation of an object later while still preserving the original
488 API.
489
490 An accessor lets you add additional code around attribute access. For
491 example, you could apply a default to an attribute that wasn't set in
492 the constructor, or you could validate that a new value for the
493 attribute is acceptable.
494
495 Finally, using accessors makes inheritance much simpler. Subclasses can
496 use the accessors rather than having to know how a parent class is
497 implemented internally.
498
499 Writing Accessors
500
501 As with constructors, Perl provides no special accessor declaration
502 syntax, so classes must provide explicitly written accessor methods.
503 There are two common types of accessors, read-only and read-write.
504
505 A simple read-only accessor simply gets the value of a single
506 attribute:
507
508 sub path {
509 my $self = shift;
510
511 return $self->{path};
512 }
513
514 A read-write accessor will allow the caller to set the value as well as
515 get it:
516
517 sub path {
518 my $self = shift;
519
520 if (@_) {
521 $self->{path} = shift;
522 }
523
524 return $self->{path};
525 }
526
527 An Aside About Smarter and Safer Code
528 Our constructor and accessors are not very smart. They don't check that
529 a $path is defined, nor do they check that a $path is a valid
530 filesystem path.
531
532 Doing these checks by hand can quickly become tedious. Writing a bunch
533 of accessors by hand is also incredibly tedious. There are a lot of
534 modules on CPAN that can help you write safer and more concise code,
535 including the modules we recommend in perlootut.
536
537 Method Call Variations
538 Perl supports several other ways to call methods besides the
539 "$object->method()" usage we've seen so far.
540
541 Method Names with a Fully Qualified Name
542
543 Perl allows you to call methods using their fully qualified name (the
544 package and method name):
545
546 my $mp3 = File::MP3->new( 'Regin.mp3', $data );
547 $mp3->File::save();
548
549 When you a fully qualified method name like "File::save", the method
550 resolution search for the "save" method starts in the "File" class,
551 skipping any "save" method the "File::MP3" class may have defined. It
552 still searches the "File" class's parents if necessary.
553
554 While this feature is most commonly used to explicitly call methods
555 inherited from an ancestor class, there is no technical restriction
556 that enforces this:
557
558 my $obj = Tree->new();
559 $obj->Dog::bark();
560
561 This calls the "bark" method from class "Dog" on an object of class
562 "Tree", even if the two classes are completely unrelated. Use this with
563 great care.
564
565 The "SUPER" pseudo-class that was described earlier is not the same as
566 calling a method with a fully-qualified name. See the earlier
567 "Inheritance" section for details.
568
569 Method Names as Strings
570
571 Perl lets you use a scalar variable containing a string as a method
572 name:
573
574 my $file = File->new( $path, $data );
575
576 my $method = 'save';
577 $file->$method();
578
579 This works exactly like calling "$file->save()". This can be very
580 useful for writing dynamic code. For example, it allows you to pass a
581 method name to be called as a parameter to another method.
582
583 Class Names as Strings
584
585 Perl also lets you use a scalar containing a string as a class name:
586
587 my $class = 'File';
588
589 my $file = $class->new( $path, $data );
590
591 Again, this allows for very dynamic code.
592
593 Subroutine References as Methods
594
595 You can also use a subroutine reference as a method:
596
597 my $sub = sub {
598 my $self = shift;
599
600 $self->save();
601 };
602
603 $file->$sub();
604
605 This is exactly equivalent to writing "$sub->($file)". You may see this
606 idiom in the wild combined with a call to "can":
607
608 if ( my $meth = $object->can('foo') ) {
609 $object->$meth();
610 }
611
612 Dereferencing Method Call
613
614 Perl also lets you use a dereferenced scalar reference in a method
615 call. That's a mouthful, so let's look at some code:
616
617 $file->${ \'save' };
618 $file->${ returns_scalar_ref() };
619 $file->${ \( returns_scalar() ) };
620 $file->${ returns_ref_to_sub_ref() };
621
622 This works if the dereference produces a string or a subroutine
623 reference.
624
625 Method Calls on Filehandles
626
627 Under the hood, Perl filehandles are instances of the "IO::Handle" or
628 "IO::File" class. Once you have an open filehandle, you can call
629 methods on it. Additionally, you can call methods on the "STDIN",
630 "STDOUT", and "STDERR" filehandles.
631
632 open my $fh, '>', 'path/to/file';
633 $fh->autoflush();
634 $fh->print('content');
635
636 STDOUT->autoflush();
637
638 Invoking Class Methods
639 Because Perl allows you to use barewords for package names and
640 subroutine names, it sometimes interprets a bareword's meaning
641 incorrectly. For example, the construct "Class->new()" can be
642 interpreted as either "'Class'->new()" or "Class()->new()". In
643 English, that second interpretation reads as "call a subroutine named
644 Class(), then call new() as a method on the return value of Class()".
645 If there is a subroutine named "Class()" in the current namespace, Perl
646 will always interpret "Class->new()" as the second alternative: a call
647 to "new()" on the object returned by a call to "Class()"
648
649 You can force Perl to use the first interpretation (i.e. as a method
650 call on the class named "Class") in two ways. First, you can append a
651 "::" to the class name:
652
653 Class::->new()
654
655 Perl will always interpret this as a method call.
656
657 Alternatively, you can quote the class name:
658
659 'Class'->new()
660
661 Of course, if the class name is in a scalar Perl will do the right
662 thing as well:
663
664 my $class = 'Class';
665 $class->new();
666
667 Indirect Object Syntax
668
669 Outside of the file handle case, use of this syntax is discouraged as
670 it can confuse the Perl interpreter. See below for more details.
671
672 Perl supports another method invocation syntax called "indirect object"
673 notation. This syntax is called "indirect" because the method comes
674 before the object it is being invoked on.
675
676 This syntax can be used with any class or object method:
677
678 my $file = new File $path, $data;
679 save $file;
680
681 We recommend that you avoid this syntax, for several reasons.
682
683 First, it can be confusing to read. In the above example, it's not
684 clear if "save" is a method provided by the "File" class or simply a
685 subroutine that expects a file object as its first argument.
686
687 When used with class methods, the problem is even worse. Because Perl
688 allows subroutine names to be written as barewords, Perl has to guess
689 whether the bareword after the method is a class name or subroutine
690 name. In other words, Perl can resolve the syntax as either "File->new(
691 $path, $data )" or "new( File( $path, $data ) )".
692
693 To parse this code, Perl uses a heuristic based on what package names
694 it has seen, what subroutines exist in the current package, what
695 barewords it has previously seen, and other input. Needless to say,
696 heuristics can produce very surprising results!
697
698 Older documentation (and some CPAN modules) encouraged this syntax,
699 particularly for constructors, so you may still find it in the wild.
700 However, we encourage you to avoid using it in new code.
701
702 You can force Perl to interpret the bareword as a class name by
703 appending "::" to it, like we saw earlier:
704
705 my $file = new File:: $path, $data;
706
707 "bless", "blessed", and "ref"
708 As we saw earlier, an object is simply a data structure that has been
709 blessed into a class via the "bless" function. The "bless" function can
710 take either one or two arguments:
711
712 my $object = bless {}, $class;
713 my $object = bless {};
714
715 In the first form, the anonymous hash is being blessed into the class
716 in $class. In the second form, the anonymous hash is blessed into the
717 current package.
718
719 The second form is strongly discouraged, because it breaks the ability
720 of a subclass to reuse the parent's constructor, but you may still run
721 across it in existing code.
722
723 If you want to know whether a particular scalar refers to an object,
724 you can use the "blessed" function exported by Scalar::Util, which is
725 shipped with the Perl core.
726
727 use Scalar::Util 'blessed';
728
729 if ( defined blessed($thing) ) { ... }
730
731 If $thing refers to an object, then this function returns the name of
732 the package the object has been blessed into. If $thing doesn't contain
733 a reference to a blessed object, the "blessed" function returns
734 "undef".
735
736 Note that "blessed($thing)" will also return false if $thing has been
737 blessed into a class named "0". This is a possible, but quite
738 pathological. Don't create a class named "0" unless you know what
739 you're doing.
740
741 Similarly, Perl's built-in "ref" function treats a reference to a
742 blessed object specially. If you call "ref($thing)" and $thing holds a
743 reference to an object, it will return the name of the class that the
744 object has been blessed into.
745
746 If you simply want to check that a variable contains an object
747 reference, we recommend that you use "defined blessed($object)", since
748 "ref" returns true values for all references, not just objects.
749
750 The UNIVERSAL Class
751 All classes automatically inherit from the UNIVERSAL class, which is
752 built-in to the Perl core. This class provides a number of methods, all
753 of which can be called on either a class or an object. You can also
754 choose to override some of these methods in your class. If you do so,
755 we recommend that you follow the built-in semantics described below.
756
757 isa($class)
758 The "isa" method returns true if the object is a member of the
759 class in $class, or a member of a subclass of $class.
760
761 If you override this method, it should never throw an exception.
762
763 DOES($role)
764 The "DOES" method returns true if its object claims to perform the
765 role $role. By default, this is equivalent to "isa". This method is
766 provided for use by object system extensions that implement roles,
767 like "Moose" and "Role::Tiny".
768
769 You can also override "DOES" directly in your own classes. If you
770 override this method, it should never throw an exception.
771
772 can($method)
773 The "can" method checks to see if the class or object it was called
774 on has a method named $method. This checks for the method in the
775 class and all of its parents. If the method exists, then a
776 reference to the subroutine is returned. If it does not then
777 "undef" is returned.
778
779 If your class responds to method calls via "AUTOLOAD", you may want
780 to overload "can" to return a subroutine reference for methods
781 which your "AUTOLOAD" method handles.
782
783 If you override this method, it should never throw an exception.
784
785 VERSION($need)
786 The "VERSION" method returns the version number of the class
787 (package).
788
789 If the $need argument is given then it will check that the current
790 version (as defined by the $VERSION variable in the package) is
791 greater than or equal to $need; it will die if this is not the
792 case. This method is called automatically by the "VERSION" form of
793 "use".
794
795 use Package 1.2 qw(some imported subs);
796 # implies:
797 Package->VERSION(1.2);
798
799 We recommend that you use this method to access another package's
800 version, rather than looking directly at $Package::VERSION. The
801 package you are looking at could have overridden the "VERSION"
802 method.
803
804 We also recommend using this method to check whether a module has a
805 sufficient version. The internal implementation uses the version
806 module to make sure that different types of version numbers are
807 compared correctly.
808
809 AUTOLOAD
810 If you call a method that doesn't exist in a class, Perl will throw an
811 error. However, if that class or any of its parent classes defines an
812 "AUTOLOAD" method, that "AUTOLOAD" method is called instead.
813
814 "AUTOLOAD" is called as a regular method, and the caller will not know
815 the difference. Whatever value your "AUTOLOAD" method returns is
816 returned to the caller.
817
818 The fully qualified method name that was called is available in the
819 $AUTOLOAD package global for your class. Since this is a global, if you
820 want to refer to do it without a package name prefix under "strict
821 'vars'", you need to declare it.
822
823 # XXX - this is a terrible way to implement accessors, but it makes
824 # for a simple example.
825 our $AUTOLOAD;
826 sub AUTOLOAD {
827 my $self = shift;
828
829 # Remove qualifier from original method name...
830 my $called = $AUTOLOAD =~ s/.*:://r;
831
832 # Is there an attribute of that name?
833 die "No such attribute: $called"
834 unless exists $self->{$called};
835
836 # If so, return it...
837 return $self->{$called};
838 }
839
840 sub DESTROY { } # see below
841
842 Without the "our $AUTOLOAD" declaration, this code will not compile
843 under the strict pragma.
844
845 As the comment says, this is not a good way to implement accessors.
846 It's slow and too clever by far. However, you may see this as a way to
847 provide accessors in older Perl code. See perlootut for recommendations
848 on OO coding in Perl.
849
850 If your class does have an "AUTOLOAD" method, we strongly recommend
851 that you override "can" in your class as well. Your overridden "can"
852 method should return a subroutine reference for any method that your
853 "AUTOLOAD" responds to.
854
855 Destructors
856 When the last reference to an object goes away, the object is
857 destroyed. If you only have one reference to an object stored in a
858 lexical scalar, the object is destroyed when that scalar goes out of
859 scope. If you store the object in a package global, that object may not
860 go out of scope until the program exits.
861
862 If you want to do something when the object is destroyed, you can
863 define a "DESTROY" method in your class. This method will always be
864 called by Perl at the appropriate time, unless the method is empty.
865
866 This is called just like any other method, with the object as the first
867 argument. It does not receive any additional arguments. However, the
868 $_[0] variable will be read-only in the destructor, so you cannot
869 assign a value to it.
870
871 If your "DESTROY" method throws an error, this error will be ignored.
872 It will not be sent to "STDERR" and it will not cause the program to
873 die. However, if your destructor is running inside an "eval {}" block,
874 then the error will change the value of $@.
875
876 Because "DESTROY" methods can be called at any time, you should
877 localize any global variables you might update in your "DESTROY". In
878 particular, if you use "eval {}" you should localize $@, and if you use
879 "system" or backticks you should localize $?.
880
881 If you define an "AUTOLOAD" in your class, then Perl will call your
882 "AUTOLOAD" to handle the "DESTROY" method. You can prevent this by
883 defining an empty "DESTROY", like we did in the autoloading example.
884 You can also check the value of $AUTOLOAD and return without doing
885 anything when called to handle "DESTROY".
886
887 Global Destruction
888
889 The order in which objects are destroyed during the global destruction
890 before the program exits is unpredictable. This means that any objects
891 contained by your object may already have been destroyed. You should
892 check that a contained object is defined before calling a method on it:
893
894 sub DESTROY {
895 my $self = shift;
896
897 $self->{handle}->close() if $self->{handle};
898 }
899
900 You can use the "${^GLOBAL_PHASE}" variable to detect if you are
901 currently in the global destruction phase:
902
903 sub DESTROY {
904 my $self = shift;
905
906 return if ${^GLOBAL_PHASE} eq 'DESTRUCT';
907
908 $self->{handle}->close();
909 }
910
911 Note that this variable was added in Perl 5.14.0. If you want to detect
912 the global destruction phase on older versions of Perl, you can use the
913 "Devel::GlobalDestruction" module on CPAN.
914
915 If your "DESTROY" method issues a warning during global destruction,
916 the Perl interpreter will append the string " during global
917 destruction" to the warning.
918
919 During global destruction, Perl will always garbage collect objects
920 before unblessed references. See "PERL_DESTRUCT_LEVEL" in perlhacktips
921 for more information about global destruction.
922
923 Non-Hash Objects
924 All the examples so far have shown objects based on a blessed hash.
925 However, it's possible to bless any type of data structure or referent,
926 including scalars, globs, and subroutines. You may see this sort of
927 thing when looking at code in the wild.
928
929 Here's an example of a module as a blessed scalar:
930
931 package Time;
932
933 use strict;
934 use warnings;
935
936 sub new {
937 my $class = shift;
938
939 my $time = time;
940 return bless \$time, $class;
941 }
942
943 sub epoch {
944 my $self = shift;
945 return ${ $self };
946 }
947
948 my $time = Time->new();
949 print $time->epoch();
950
951 Inside-Out objects
952 In the past, the Perl community experimented with a technique called
953 "inside-out objects". An inside-out object stores its data outside of
954 the object's reference, indexed on a unique property of the object,
955 such as its memory address, rather than in the object itself. This has
956 the advantage of enforcing the encapsulation of object attributes,
957 since their data is not stored in the object itself.
958
959 This technique was popular for a while (and was recommended in Damian
960 Conway's Perl Best Practices), but never achieved universal adoption.
961 The Object::InsideOut module on CPAN provides a comprehensive
962 implementation of this technique, and you may see it or other inside-
963 out modules in the wild.
964
965 Here is a simple example of the technique, using the
966 Hash::Util::FieldHash core module. This module was added to the core to
967 support inside-out object implementations.
968
969 package Time;
970
971 use strict;
972 use warnings;
973
974 use Hash::Util::FieldHash 'fieldhash';
975
976 fieldhash my %time_for;
977
978 sub new {
979 my $class = shift;
980
981 my $self = bless \( my $object ), $class;
982
983 $time_for{$self} = time;
984
985 return $self;
986 }
987
988 sub epoch {
989 my $self = shift;
990
991 return $time_for{$self};
992 }
993
994 my $time = Time->new;
995 print $time->epoch;
996
997 Pseudo-hashes
998 The pseudo-hash feature was an experimental feature introduced in
999 earlier versions of Perl and removed in 5.10.0. A pseudo-hash is an
1000 array reference which can be accessed using named keys like a hash. You
1001 may run in to some code in the wild which uses it. See the fields
1002 pragma for more information.
1003
1005 A kinder, gentler tutorial on object-oriented programming in Perl can
1006 be found in perlootut. You should also check out perlmodlib for some
1007 style guides on constructing both modules and classes.
1008
1009
1010
1011perl v5.26.3 2018-03-23 PERLOBJ(1)