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

PERL OO SYSTEMS

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

CONCLUSION

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