1PERLOOTUT(1)           Perl Programmers Reference Guide           PERLOOTUT(1)
2
3
4

NAME

6       perlootut - Object-Oriented Programming in Perl Tutorial
7

DATE

9       This document was created in February, 2011, and the last major
10       revision was in February, 2013.
11
12       If you are reading this in the future then it's possible that the state
13       of the art has changed. We recommend you start by reading the perlootut
14       document in the latest stable release of Perl, rather than this
15       version.
16

DESCRIPTION

18       This document provides an introduction to object-oriented programming
19       in Perl. It begins with a brief overview of the concepts behind object
20       oriented design. Then it introduces several different OO systems from
21       CPAN <https://www.cpan.org> which build on top of what Perl provides.
22
23       By default, Perl's built-in OO system is very minimal, leaving you to
24       do most of the work. This minimalism made a lot of sense in 1994, but
25       in the years since Perl 5.0 we've seen a number of common patterns
26       emerge in Perl OO. Fortunately, Perl's flexibility has allowed a rich
27       ecosystem of Perl OO systems to flourish.
28
29       If you want to know how Perl OO works under the hood, the perlobj
30       document explains the nitty gritty details.
31
32       This document assumes that you already understand the basics of Perl
33       syntax, variable types, operators, and subroutine calls. If you don't
34       understand these concepts yet, please read perlintro first. You should
35       also read the perlsyn, perlop, and perlsub documents.
36

OBJECT-ORIENTED FUNDAMENTALS

38       Most object systems share a number of common concepts. You've probably
39       heard terms like "class", "object, "method", and "attribute" before.
40       Understanding the concepts will make it much easier to read and write
41       object-oriented code. If you're already familiar with these terms, you
42       should still skim this section, since it explains each concept in terms
43       of Perl's OO implementation.
44
45       Perl's OO system is class-based. Class-based OO is fairly common. It's
46       used by Java, C++, C#, Python, Ruby, and many other languages. There
47       are other object orientation paradigms as well. JavaScript is the most
48       popular language to use another paradigm. JavaScript's OO system is
49       prototype-based.
50
51   Object
52       An object is a data structure that bundles together data and
53       subroutines which operate on that data. An object's data is called
54       attributes, and its subroutines are called methods. An object can be
55       thought of as a noun (a person, a web service, a computer).
56
57       An object represents a single discrete thing. For example, an object
58       might represent a file. The attributes for a file object might include
59       its path, content, and last modification time. If we created an object
60       to represent /etc/hostname on a machine named "foo.example.com", that
61       object's path would be "/etc/hostname", its content would be "foo\n",
62       and it's last modification time would be 1304974868 seconds since the
63       beginning of the epoch.
64
65       The methods associated with a file might include rename() and write().
66
67       In Perl most objects are hashes, but the OO systems we recommend keep
68       you from having to worry about this. In practice, it's best to consider
69       an object's internal data structure opaque.
70
71   Class
72       A class defines the behavior of a category of objects. A class is a
73       name for a category (like "File"), and a class also defines the
74       behavior of objects in that category.
75
76       All objects belong to a specific class. For example, our /etc/hostname
77       object belongs to the "File" class. When we want to create a specific
78       object, we start with its class, and construct or instantiate an
79       object. A specific object is often referred to as an instance of a
80       class.
81
82       In Perl, any package can be a class. The difference between a package
83       which is a class and one which isn't is based on how the package is
84       used. Here's our "class declaration" for the "File" class:
85
86         package File;
87
88       In Perl, there is no special keyword for constructing an object.
89       However, most OO modules on CPAN use a method named new() to construct
90       a new object:
91
92         my $hostname = File->new(
93             path          => '/etc/hostname',
94             content       => "foo\n",
95             last_mod_time => 1304974868,
96         );
97
98       (Don't worry about that "->" operator, it will be explained later.)
99
100       Blessing
101
102       As we said earlier, most Perl objects are hashes, but an object can be
103       an instance of any Perl data type (scalar, array, etc.). Turning a
104       plain data structure into an object is done by blessing that data
105       structure using Perl's "bless" function.
106
107       While we strongly suggest you don't build your objects from scratch,
108       you should know the term bless. A blessed data structure (aka "a
109       referent") is an object. We sometimes say that an object has been
110       "blessed into a class".
111
112       Once a referent has been blessed, the "blessed" function from the
113       Scalar::Util core module can tell us its class name. This subroutine
114       returns an object's class when passed an object, and false otherwise.
115
116         use Scalar::Util 'blessed';
117
118         print blessed($hash);      # undef
119         print blessed($hostname);  # File
120
121       Constructor
122
123       A constructor creates a new object. In Perl, a class's constructor is
124       just another method, unlike some other languages, which provide syntax
125       for constructors. Most Perl classes use "new" as the name for their
126       constructor:
127
128         my $file = File->new(...);
129
130   Methods
131       You already learned that a method is a subroutine that operates on an
132       object. You can think of a method as the things that an object can do.
133       If an object is a noun, then methods are its verbs (save, print, open).
134
135       In Perl, methods are simply subroutines that live in a class's package.
136       Methods are always written to receive the object as their first
137       argument:
138
139         sub print_info {
140             my $self = shift;
141
142             print "This file is at ", $self->path, "\n";
143         }
144
145         $file->print_info;
146         # The file is at /etc/hostname
147
148       What makes a method special is how it's called. The arrow operator
149       ("->") tells Perl that we are calling a method.
150
151       When we make a method call, Perl arranges for the method's invocant to
152       be passed as the first argument. Invocant is a fancy name for the thing
153       on the left side of the arrow. The invocant can either be a class name
154       or an object. We can also pass additional arguments to the method:
155
156         sub print_info {
157             my $self   = shift;
158             my $prefix = shift // "This file is at ";
159
160             print $prefix, ", ", $self->path, "\n";
161         }
162
163         $file->print_info("The file is located at ");
164         # The file is located at /etc/hostname
165
166   Attributes
167       Each class can define its attributes. When we instantiate an object, we
168       assign values to those attributes. For example, every "File" object has
169       a path. Attributes are sometimes called properties.
170
171       Perl has no special syntax for attributes. Under the hood, attributes
172       are often stored as keys in the object's underlying hash, but don't
173       worry about this.
174
175       We recommend that you only access attributes via accessor methods.
176       These are methods that can get or set the value of each attribute. We
177       saw this earlier in the print_info() example, which calls
178       "$self->path".
179
180       You might also see the terms getter and setter. These are two types of
181       accessors. A getter gets the attribute's value, while a setter sets it.
182       Another term for a setter is mutator
183
184       Attributes are typically defined as read-only or read-write. Read-only
185       attributes can only be set when the object is first created, while
186       read-write attributes can be altered at any time.
187
188       The value of an attribute may itself be another object. For example,
189       instead of returning its last mod time as a number, the "File" class
190       could return a DateTime object representing that value.
191
192       It's possible to have a class that does not expose any publicly
193       settable attributes. Not every class has attributes and methods.
194
195   Polymorphism
196       Polymorphism is a fancy way of saying that objects from two different
197       classes share an API. For example, we could have "File" and "WebPage"
198       classes which both have a print_content() method. This method might
199       produce different output for each class, but they share a common
200       interface.
201
202       While the two classes may differ in many ways, when it comes to the
203       print_content() method, they are the same. This means that we can try
204       to call the print_content() method on an object of either class, and we
205       don't have to know what class the object belongs to!
206
207       Polymorphism is one of the key concepts of object-oriented design.
208
209   Inheritance
210       Inheritance lets you create a specialized version of an existing class.
211       Inheritance lets the new class reuse the methods and attributes of
212       another class.
213
214       For example, we could create an "File::MP3" class which inherits from
215       "File". An "File::MP3" is-a more specific type of "File".  All mp3
216       files are files, but not all files are mp3 files.
217
218       We often refer to inheritance relationships as parent-child or
219       "superclass"/"subclass" relationships. Sometimes we say that the child
220       has an is-a relationship with its parent class.
221
222       "File" is a superclass of "File::MP3", and "File::MP3" is a subclass of
223       "File".
224
225         package File::MP3;
226
227         use parent 'File';
228
229       The parent module is one of several ways that Perl lets you define
230       inheritance relationships.
231
232       Perl allows multiple inheritance, which means that a class can inherit
233       from multiple parents. While this is possible, we strongly recommend
234       against it. Generally, you can use roles to do everything you can do
235       with multiple inheritance, but in a cleaner way.
236
237       Note that there's nothing wrong with defining multiple subclasses of a
238       given class. This is both common and safe. For example, we might define
239       "File::MP3::FixedBitrate" and "File::MP3::VariableBitrate" classes to
240       distinguish between different types of mp3 file.
241
242       Overriding methods and method resolution
243
244       Inheritance allows two classes to share code. By default, every method
245       in the parent class is also available in the child. The child can
246       explicitly override a parent's method to provide its own
247       implementation. For example, if we have an "File::MP3" object, it has
248       the print_info() method from "File":
249
250         my $cage = File::MP3->new(
251             path          => 'mp3s/My-Body-Is-a-Cage.mp3',
252             content       => $mp3_data,
253             last_mod_time => 1304974868,
254             title         => 'My Body Is a Cage',
255         );
256
257         $cage->print_info;
258         # The file is at mp3s/My-Body-Is-a-Cage.mp3
259
260       If we wanted to include the mp3's title in the greeting, we could
261       override the method:
262
263         package File::MP3;
264
265         use parent 'File';
266
267         sub print_info {
268             my $self = shift;
269
270             print "This file is at ", $self->path, "\n";
271             print "Its title is ", $self->title, "\n";
272         }
273
274         $cage->print_info;
275         # The file is at mp3s/My-Body-Is-a-Cage.mp3
276         # Its title is My Body Is a Cage
277
278       The process of determining what method should be used is called method
279       resolution. What Perl does is look at the object's class first
280       ("File::MP3" in this case). If that class defines the method, then that
281       class's version of the method is called. If not, Perl looks at each
282       parent class in turn. For "File::MP3", its only parent is "File". If
283       "File::MP3" does not define the method, but "File" does, then Perl
284       calls the method in "File".
285
286       If "File" inherited from "DataSource", which inherited from "Thing",
287       then Perl would keep looking "up the chain" if necessary.
288
289       It is possible to explicitly call a parent method from a child:
290
291         package File::MP3;
292
293         use parent 'File';
294
295         sub print_info {
296             my $self = shift;
297
298             $self->SUPER::print_info();
299             print "Its title is ", $self->title, "\n";
300         }
301
302       The "SUPER::" bit tells Perl to look for the print_info() in the
303       "File::MP3" class's inheritance chain. When it finds the parent class
304       that implements this method, the method is called.
305
306       We mentioned multiple inheritance earlier. The main problem with
307       multiple inheritance is that it greatly complicates method resolution.
308       See perlobj for more details.
309
310   Encapsulation
311       Encapsulation is the idea that an object is opaque. When another
312       developer uses your class, they don't need to know how it is
313       implemented, they just need to know what it does.
314
315       Encapsulation is important for several reasons. First, it allows you to
316       separate the public API from the private implementation. This means you
317       can change that implementation without breaking the API.
318
319       Second, when classes are well encapsulated, they become easier to
320       subclass. Ideally, a subclass uses the same APIs to access object data
321       that its parent class uses. In reality, subclassing sometimes involves
322       violating encapsulation, but a good API can minimize the need to do
323       this.
324
325       We mentioned earlier that most Perl objects are implemented as hashes
326       under the hood. The principle of encapsulation tells us that we should
327       not rely on this. Instead, we should use accessor methods to access the
328       data in that hash. The object systems that we recommend below all
329       automate the generation of accessor methods. If you use one of them,
330       you should never have to access the object as a hash directly.
331
332   Composition
333       In object-oriented code, we often find that one object references
334       another object. This is called composition, or a has-a relationship.
335
336       Earlier, we mentioned that the "File" class's "last_mod_time" accessor
337       could return a DateTime object. This is a perfect example of
338       composition. We could go even further, and make the "path" and
339       "content" accessors return objects as well. The "File" class would then
340       be composed of several other objects.
341
342   Roles
343       Roles are something that a class does, rather than something that it
344       is. Roles are relatively new to Perl, but have become rather popular.
345       Roles are applied to classes. Sometimes we say that classes consume
346       roles.
347
348       Roles are an alternative to inheritance for providing polymorphism.
349       Let's assume we have two classes, "Radio" and "Computer". Both of these
350       things have on/off switches. We want to model that in our class
351       definitions.
352
353       We could have both classes inherit from a common parent, like
354       "Machine", but not all machines have on/off switches. We could create a
355       parent class called "HasOnOffSwitch", but that is very artificial.
356       Radios and computers are not specializations of this parent. This
357       parent is really a rather ridiculous creation.
358
359       This is where roles come in. It makes a lot of sense to create a
360       "HasOnOffSwitch" role and apply it to both classes. This role would
361       define a known API like providing turn_on() and turn_off() methods.
362
363       Perl does not have any built-in way to express roles. In the past,
364       people just bit the bullet and used multiple inheritance. Nowadays,
365       there are several good choices on CPAN for using roles.
366
367   When to Use OO
368       Object Orientation is not the best solution to every problem. In Perl
369       Best Practices (copyright 2004, Published by O'Reilly Media, Inc.),
370       Damian Conway provides a list of criteria to use when deciding if OO is
371       the right fit for your problem:
372
373       •   The system being designed is large, or is likely to become large.
374
375       •   The data can be aggregated into obvious structures, especially if
376           there's a large amount of data in each aggregate.
377
378       •   The various types of data aggregate form a natural hierarchy that
379           facilitates the use of inheritance and polymorphism.
380
381       •   You have a piece of data on which many different operations are
382           applied.
383
384       •   You need to perform the same general operations on related types of
385           data, but with slight variations depending on the specific type of
386           data the operations are applied to.
387
388       •   It's likely you'll have to add new data types later.
389
390       •   The typical interactions between pieces of data are best
391           represented by operators.
392
393       •   The implementation of individual components of the system is likely
394           to change over time.
395
396       •   The system design is already object-oriented.
397
398       •   Large numbers of other programmers will be using your code modules.
399

PERL OO SYSTEMS

401       As we mentioned before, Perl's built-in OO system is very minimal, but
402       also quite flexible. Over the years, many people have developed systems
403       which build on top of Perl's built-in system to provide more features
404       and convenience.
405
406       We strongly recommend that you use one of these systems. Even the most
407       minimal of them eliminates a lot of repetitive boilerplate. There's
408       really no good reason to write your classes from scratch in Perl.
409
410       If you are interested in the guts underlying these systems, check out
411       perlobj.
412
413   Moose
414       Moose bills itself as a "postmodern object system for Perl 5". Don't be
415       scared, the "postmodern" label is a callback to Larry's description of
416       Perl as "the first postmodern computer language".
417
418       "Moose" provides a complete, modern OO system. Its biggest influence is
419       the Common Lisp Object System, but it also borrows ideas from Smalltalk
420       and several other languages. "Moose" was created by Stevan Little, and
421       draws heavily from his work on the Raku OO design.
422
423       Here is our "File" class using "Moose":
424
425         package File;
426         use Moose;
427
428         has path          => ( is => 'ro' );
429         has content       => ( is => 'ro' );
430         has last_mod_time => ( is => 'ro' );
431
432         sub print_info {
433             my $self = shift;
434
435             print "This file is at ", $self->path, "\n";
436         }
437
438       "Moose" provides a number of features:
439
440       •   Declarative sugar
441
442           "Moose" provides a layer of declarative "sugar" for defining
443           classes.  That sugar is just a set of exported functions that make
444           declaring how your class works simpler and more palatable.  This
445           lets you describe what your class is, rather than having to tell
446           Perl how to implement your class.
447
448           The has() subroutine declares an attribute, and "Moose"
449           automatically creates accessors for these attributes. It also takes
450           care of creating a new() method for you. This constructor knows
451           about the attributes you declared, so you can set them when
452           creating a new "File".
453
454       •   Roles built-in
455
456           "Moose" lets you define roles the same way you define classes:
457
458             package HasOnOffSwitch;
459             use Moose::Role;
460
461             has is_on => (
462                 is  => 'rw',
463                 isa => 'Bool',
464             );
465
466             sub turn_on {
467                 my $self = shift;
468                 $self->is_on(1);
469             }
470
471             sub turn_off {
472                 my $self = shift;
473                 $self->is_on(0);
474             }
475
476       •   A miniature type system
477
478           In the example above, you can see that we passed "isa => 'Bool'" to
479           has() when creating our "is_on" attribute. This tells "Moose" that
480           this attribute must be a boolean value. If we try to set it to an
481           invalid value, our code will throw an error.
482
483       •   Full introspection and manipulation
484
485           Perl's built-in introspection features are fairly minimal. "Moose"
486           builds on top of them and creates a full introspection layer for
487           your classes. This lets you ask questions like "what methods does
488           the File class implement?" It also lets you modify your classes
489           programmatically.
490
491       •   Self-hosted and extensible
492
493           "Moose" describes itself using its own introspection API. Besides
494           being a cool trick, this means that you can extend "Moose" using
495           "Moose" itself.
496
497       •   Rich ecosystem
498
499           There is a rich ecosystem of "Moose" extensions on CPAN under the
500           MooseX <https://metacpan.org/search?q=MooseX> namespace. In
501           addition, many modules on CPAN already use "Moose", providing you
502           with lots of examples to learn from.
503
504       •   Many more features
505
506           "Moose" is a very powerful tool, and we can't cover all of its
507           features here. We encourage you to learn more by reading the
508           "Moose" documentation, starting with Moose::Manual
509           <https://metacpan.org/pod/Moose::Manual>.
510
511       Of course, "Moose" isn't perfect.
512
513       "Moose" can make your code slower to load. "Moose" itself is not small,
514       and it does a lot of code generation when you define your class. This
515       code generation means that your runtime code is as fast as it can be,
516       but you pay for this when your modules are first loaded.
517
518       This load time hit can be a problem when startup speed is important,
519       such as with a command-line script or a "plain vanilla" CGI script that
520       must be loaded each time it is executed.
521
522       Before you panic, know that many people do use "Moose" for command-line
523       tools and other startup-sensitive code. We encourage you to try "Moose"
524       out first before worrying about startup speed.
525
526       "Moose" also has several dependencies on other modules. Most of these
527       are small stand-alone modules, a number of which have been spun off
528       from "Moose". "Moose" itself, and some of its dependencies, require a
529       compiler. If you need to install your software on a system without a
530       compiler, or if having any dependencies is a problem, then "Moose" may
531       not be right for you.
532
533       Moo
534
535       If you try "Moose" and find that one of these issues is preventing you
536       from using "Moose", we encourage you to consider Moo next. "Moo"
537       implements a subset of "Moose"'s functionality in a simpler package.
538       For most features that it does implement, the end-user API is identical
539       to "Moose", meaning you can switch from "Moo" to "Moose" quite easily.
540
541       "Moo" does not implement most of "Moose"'s introspection API, so it's
542       often faster when loading your modules. Additionally, none of its
543       dependencies require XS, so it can be installed on machines without a
544       compiler.
545
546       One of "Moo"'s most compelling features is its interoperability with
547       "Moose". When someone tries to use "Moose"'s introspection API on a
548       "Moo" class or role, it is transparently inflated into a "Moose" class
549       or role. This makes it easier to incorporate "Moo"-using code into a
550       "Moose" code base and vice versa.
551
552       For example, a "Moose" class can subclass a "Moo" class using "extends"
553       or consume a "Moo" role using "with".
554
555       The "Moose" authors hope that one day "Moo" can be made obsolete by
556       improving "Moose" enough, but for now it provides a worthwhile
557       alternative to "Moose".
558
559   Class::Accessor
560       Class::Accessor is the polar opposite of "Moose". It provides very few
561       features, nor is it self-hosting.
562
563       It is, however, very simple, pure Perl, and it has no non-core
564       dependencies. It also provides a "Moose-like" API on demand for the
565       features it supports.
566
567       Even though it doesn't do much, it is still preferable to writing your
568       own classes from scratch.
569
570       Here's our "File" class with "Class::Accessor":
571
572         package File;
573         use Class::Accessor 'antlers';
574
575         has path          => ( is => 'ro' );
576         has content       => ( is => 'ro' );
577         has last_mod_time => ( is => 'ro' );
578
579         sub print_info {
580             my $self = shift;
581
582             print "This file is at ", $self->path, "\n";
583         }
584
585       The "antlers" import flag tells "Class::Accessor" that you want to
586       define your attributes using "Moose"-like syntax. The only parameter
587       that you can pass to "has" is "is". We recommend that you use this
588       Moose-like syntax if you choose "Class::Accessor" since it means you
589       will have a smoother upgrade path if you later decide to move to
590       "Moose".
591
592       Like "Moose", "Class::Accessor" generates accessor methods and a
593       constructor for your class.
594
595   Class::Tiny
596       Finally, we have Class::Tiny. This module truly lives up to its name.
597       It has an incredibly minimal API and absolutely no dependencies on any
598       recent Perl. Still, we think it's a lot easier to use than writing your
599       own OO code from scratch.
600
601       Here's our "File" class once more:
602
603         package File;
604         use Class::Tiny qw( path content last_mod_time );
605
606         sub print_info {
607             my $self = shift;
608
609             print "This file is at ", $self->path, "\n";
610         }
611
612       That's it!
613
614       With "Class::Tiny", all accessors are read-write. It generates a
615       constructor for you, as well as the accessors you define.
616
617       You can also use Class::Tiny::Antlers for "Moose"-like syntax.
618
619   Role::Tiny
620       As we mentioned before, roles provide an alternative to inheritance,
621       but Perl does not have any built-in role support. If you choose to use
622       Moose, it comes with a full-fledged role implementation. However, if
623       you use one of our other recommended OO modules, you can still use
624       roles with Role::Tiny
625
626       "Role::Tiny" provides some of the same features as Moose's role system,
627       but in a much smaller package. Most notably, it doesn't support any
628       sort of attribute declaration, so you have to do that by hand.  Still,
629       it's useful, and works well with "Class::Accessor" and "Class::Tiny"
630
631   OO System Summary
632       Here's a brief recap of the options we covered:
633
634       •   Moose
635
636           "Moose" is the maximal option. It has a lot of features, a big
637           ecosystem, and a thriving user base. We also covered Moo briefly.
638           "Moo" is "Moose" lite, and a reasonable alternative when Moose
639           doesn't work for your application.
640
641       •   Class::Accessor
642
643           "Class::Accessor" does a lot less than "Moose", and is a nice
644           alternative if you find "Moose" overwhelming. It's been around a
645           long time and is well battle-tested. It also has a minimal "Moose"
646           compatibility mode which makes moving from "Class::Accessor" to
647           "Moose" easy.
648
649       •   Class::Tiny
650
651           "Class::Tiny" is the absolute minimal option. It has no
652           dependencies, and almost no syntax to learn. It's a good option for
653           a super minimal environment and for throwing something together
654           quickly without having to worry about details.
655
656       •   Role::Tiny
657
658           Use "Role::Tiny" with "Class::Accessor" or "Class::Tiny" if you
659           find yourself considering multiple inheritance. If you go with
660           "Moose", it comes with its own role implementation.
661
662   Other OO Systems
663       There are literally dozens of other OO-related modules on CPAN besides
664       those covered here, and you're likely to run across one or more of them
665       if you work with other people's code.
666
667       In addition, plenty of code in the wild does all of its OO "by hand",
668       using just the Perl built-in OO features. If you need to maintain such
669       code, you should read perlobj to understand exactly how Perl's built-in
670       OO works.
671

CONCLUSION

673       As we said before, Perl's minimal OO system has led to a profusion of
674       OO systems on CPAN. While you can still drop down to the bare metal and
675       write your classes by hand, there's really no reason to do that with
676       modern Perl.
677
678       For small systems, Class::Tiny and Class::Accessor both provide minimal
679       object systems that take care of basic boilerplate for you.
680
681       For bigger projects, Moose provides a rich set of features that will
682       let you focus on implementing your business logic. Moo provides a nice
683       alternative to Moose when you want a lot of features but need faster
684       compile time or to avoid XS.
685
686       We encourage you to play with and evaluate Moose, Moo, Class::Accessor,
687       and Class::Tiny to see which OO system is right for you.
688
689
690
691perl v5.38.2                      2023-11-30                      PERLOOTUT(1)
Impressum