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