Debian Codegraph @

upstream/fedora-44/man1/perlootut.1

raw
1 .\" -*- mode: troff; coding: utf-8 -*-
2 .\" Automatically generated by Pod::Man v6.0.2 (Pod::Simple 3.45)
3 .\"
4 .\" Standard preamble:
5 .\" ========================================================================
6 .de Sp \" Vertical space (when we can't use .PP)
7 .if t .sp .5v
8 .if n .sp
9 ..
10 .de Vb \" Begin verbatim text
11 .ft CW
12 .nf
13 .ne \\$1
14 ..
15 .de Ve \" End verbatim text
16 .ft R
17 .fi
18 ..
19 .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>.
20 .ie n \{\
21 . ds C` ""
22 . ds C' ""
23 'br\}
24 .el\{\
25 . ds C`
26 . ds C'
27 'br\}
28 .\"
29 .\" Escape single quotes in literal strings from groff's Unicode transform.
30 .ie \n(.g .ds Aq \(aq
31 .el .ds Aq '
32 .\"
33 .\" If the F register is >0, we'll generate index entries on stderr for
34 .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
35 .\" entries marked with X<> in POD. Of course, you'll have to process the
36 .\" output yourself in some meaningful fashion.
37 .\"
38 .\" Avoid warning from groff about undefined register 'F'.
39 .de IX
40 ..
41 .nr rF 0
42 .if \n(.g .if rF .nr rF 1
43 .if (\n(rF:(\n(.g==0)) \{\
44 . if \nF \{\
45 . de IX
46 . tm Index:\\$1\t\\n%\t"\\$2"
47 ..
48 . if !\nF==2 \{\
49 . nr % 0
50 . nr F 2
51 . \}
52 . \}
53 .\}
54 .rr rF
55 .\"
56 .\" Required to disable full justification in groff 1.23.0.
57 .if n .ds AD l
58 .\" ========================================================================
59 .\"
60 .IX Title "PERLOOTUT 1"
61 .TH PERLOOTUT 1 2026-03-09 "perl v5.42.1" "Perl Programmers Reference Guide"
62 .\" For nroff, turn off justification. Always turn off hyphenation; it makes
63 .\" way too many mistakes in technical documents.
64 .if n .ad l
65 .nh
66 .SH NAME
67 perlootut \- Object\-Oriented Programming in Perl Tutorial
68 .SH DATE
69 .IX Header "DATE"
70 This document was created in February, 2011, and the last major
71 revision was in February, 2013.
72 .PP
73 If you are reading this in the future then it\*(Aqs possible that the state
74 of the art has changed. We recommend you start by reading the perlootut
75 document in the latest stable release of Perl, rather than this
76 version.
77 .SH DESCRIPTION
78 .IX Header "DESCRIPTION"
79 This document provides an introduction to object\-oriented programming
80 in Perl. It begins with a brief overview of the concepts behind object
81 oriented design. Then it introduces several different OO systems from
82 CPAN <https://www.cpan.org> which build on top of what Perl
83 provides.
84 .PP
85 By default, Perl\*(Aqs built\-in OO system is very minimal, leaving you to
86 do most of the work. This minimalism made a lot of sense in 1994, but
87 in the years since Perl 5.0 we\*(Aqve seen a number of common patterns
88 emerge in Perl OO. Fortunately, Perl\*(Aqs flexibility has allowed a rich
89 ecosystem of Perl OO systems to flourish.
90 .PP
91 If you want to know how Perl OO works under the hood, the perlobj
92 document explains the nitty gritty details.
93 .PP
94 This document assumes that you already understand the basics of Perl
95 syntax, variable types, operators, and subroutine calls. If you don\*(Aqt
96 understand these concepts yet, please read perlintro first. You
97 should also read the perlsyn, perlop, and perlsub documents.
98 .SH "OBJECT\-ORIENTED FUNDAMENTALS"
99 .IX Header "OBJECT-ORIENTED FUNDAMENTALS"
100 Most object systems share a number of common concepts. You\*(Aqve probably
101 heard terms like "class", "object, "method", and "attribute" before.
102 Understanding the concepts will make it much easier to read and write
103 object\-oriented code. If you\*(Aqre already familiar with these terms, you
104 should still skim this section, since it explains each concept in terms
105 of Perl\*(Aqs OO implementation.
106 .PP
107 Perl\*(Aqs OO system is class\-based. Class\-based OO is fairly common. It\*(Aqs
108 used by Java, C++, C#, Python, Ruby, and many other languages. There
109 are other object orientation paradigms as well. JavaScript is the most
110 popular language to use another paradigm. JavaScript\*(Aqs OO system is
111 prototype\-based.
112 .SS Object
113 .IX Subsection "Object"
114 An \fBobject\fR is a data structure that bundles together data and
115 subroutines which operate on that data. An object\*(Aqs data is called
116 \&\fBattributes\fR, and its subroutines are called \fBmethods\fR. An object can
117 be thought of as a noun (a person, a web service, a computer).
118 .PP
119 An object represents a single discrete thing. For example, an object
120 might represent a file. The attributes for a file object might include
121 its path, content, and last modification time. If we created an object
122 to represent \fI/etc/hostname\fR on a machine named "foo.example.com",
123 that object\*(Aqs path would be "/etc/hostname", its content would be
124 "foo\en", and it\*(Aqs last modification time would be 1304974868 seconds
125 since the beginning of the epoch.
126 .PP
127 The methods associated with a file might include \f(CWrename()\fR and
128 \&\f(CWwrite()\fR.
129 .PP
130 In Perl most objects are hashes, but the OO systems we recommend keep
131 you from having to worry about this. In practice, it\*(Aqs best to consider
132 an object\*(Aqs internal data structure opaque.
133 .SS Class
134 .IX Subsection "Class"
135 A \fBclass\fR defines the behavior of a category of objects. A class is a
136 name for a category (like "File"), and a class also defines the
137 behavior of objects in that category.
138 .PP
139 All objects belong to a specific class. For example, our
140 \&\fI/etc/hostname\fR object belongs to the \f(CW\*(C`File\*(C'\fR class. When we want to
141 create a specific object, we start with its class, and \fBconstruct\fR or
142 \&\fBinstantiate\fR an object. A specific object is often referred to as an
143 \&\fBinstance\fR of a class.
144 .PP
145 In Perl, any package can be a class. The difference between a package
146 which is a class and one which isn\*(Aqt is based on how the package is
147 used. Here\*(Aqs our "class declaration" for the \f(CW\*(C`File\*(C'\fR class:
148 .PP
149 .Vb 1
150 \& package File;
151 .Ve
152 .PP
153 In Perl, there is no special keyword for constructing an object.
154 However, most OO modules on CPAN use a method named \f(CWnew()\fR to
155 construct a new object:
156 .PP
157 .Vb 5
158 \& my $hostname = File\->new(
159 \& path => \*(Aq/etc/hostname\*(Aq,
160 \& content => "foo\en",
161 \& last_mod_time => 1304974868,
162 \& );
163 .Ve
164 .PP
165 (Don\*(Aqt worry about that \f(CW\*(C`\->\*(C'\fR operator, it will be explained
166 later.)
167 .PP
168 \fIBlessing\fR
169 .IX Subsection "Blessing"
170 .PP
171 As we said earlier, most Perl objects are hashes, but an object can be
172 an instance of any Perl data type (scalar, array, etc.). Turning a
173 plain data structure into an object is done by \fBblessing\fR that data
174 structure using Perl\*(Aqs \f(CW\*(C`bless\*(C'\fR function.
175 .PP
176 While we strongly suggest you don\*(Aqt build your objects from scratch,
177 you should know the term \fBbless\fR. A \fBblessed\fR data structure (aka "a
178 referent") is an object. We sometimes say that an object has been
179 "blessed into a class".
180 .PP
181 Once a referent has been blessed, the \f(CW\*(C`blessed\*(C'\fR function from the
182 Scalar::Util core module can tell us its class name. This subroutine
183 returns an object\*(Aqs class when passed an object, and false otherwise.
184 .PP
185 .Vb 1
186 \& use Scalar::Util \*(Aqblessed\*(Aq;
187 \&
188 \& print blessed($hash); # undef
189 \& print blessed($hostname); # File
190 .Ve
191 .PP
192 \fIConstructor\fR
193 .IX Subsection "Constructor"
194 .PP
195 A \fBconstructor\fR creates a new object. In Perl, a class\*(Aqs constructor
196 is just another method, unlike some other languages, which provide
197 syntax for constructors. Most Perl classes use \f(CW\*(C`new\*(C'\fR as the name for
198 their constructor:
199 .PP
200 .Vb 1
201 \& my $file = File\->new(...);
202 .Ve
203 .SS Methods
204 .IX Subsection "Methods"
205 You already learned that a \fBmethod\fR is a subroutine that operates on
206 an object. You can think of a method as the things that an object can
207 \&\fIdo\fR. If an object is a noun, then methods are its verbs (save, print,
208 open).
209 .PP
210 In Perl, methods are simply subroutines that live in a class\*(Aqs package.
211 Methods are always written to receive the object as their first
212 argument:
213 .PP
214 .Vb 2
215 \& sub print_info {
216 \& my $self = shift;
217 \&
218 \& print "This file is at ", $self\->path, "\en";
219 \& }
220 \&
221 \& $file\->print_info;
222 \& # The file is at /etc/hostname
223 .Ve
224 .PP
225 What makes a method special is \fIhow it\*(Aqs called\fR. The arrow operator
226 (\f(CW\*(C`\->\*(C'\fR) tells Perl that we are calling a method.
227 .PP
228 When we make a method call, Perl arranges for the method\*(Aqs \fBinvocant\fR
229 to be passed as the first argument. \fBInvocant\fR is a fancy name for the
230 thing on the left side of the arrow. The invocant can either be a class
231 name or an object. We can also pass additional arguments to the method:
232 .PP
233 .Vb 3
234 \& sub print_info {
235 \& my $self = shift;
236 \& my $prefix = shift // "This file is at ";
237 \&
238 \& print $prefix, ", ", $self\->path, "\en";
239 \& }
240 \&
241 \& $file\->print_info("The file is located at ");
242 \& # The file is located at /etc/hostname
243 .Ve
244 .SS Attributes
245 .IX Subsection "Attributes"
246 Each class can define its \fBattributes\fR. When we instantiate an object,
247 we assign values to those attributes. For example, every \f(CW\*(C`File\*(C'\fR object
248 has a path. Attributes are sometimes called \fBproperties\fR.
249 .PP
250 Perl has no special syntax for attributes. Under the hood, attributes
251 are often stored as keys in the object\*(Aqs underlying hash, but don\*(Aqt
252 worry about this.
253 .PP
254 We recommend that you only access attributes via \fBaccessor\fR methods.
255 These are methods that can get or set the value of each attribute. We
256 saw this earlier in the \f(CWprint_info()\fR example, which calls \f(CW\*(C`$self\->path\*(C'\fR.
257 .PP
258 You might also see the terms \fBgetter\fR and \fBsetter\fR. These are two
259 types of accessors. A getter gets the attribute\*(Aqs value, while a setter
260 sets it. Another term for a setter is \fBmutator\fR
261 .PP
262 Attributes are typically defined as read\-only or read\-write. Read\-only
263 attributes can only be set when the object is first created, while
264 read\-write attributes can be altered at any time.
265 .PP
266 The value of an attribute may itself be another object. For example,
267 instead of returning its last mod time as a number, the \f(CW\*(C`File\*(C'\fR class
268 could return a DateTime object representing that value.
269 .PP
270 It\*(Aqs possible to have a class that does not expose any publicly
271 settable attributes. Not every class has attributes and methods.
272 .SS Polymorphism
273 .IX Subsection "Polymorphism"
274 \&\fBPolymorphism\fR is a fancy way of saying that objects from two
275 different classes share an API. For example, we could have \f(CW\*(C`File\*(C'\fR and
276 \&\f(CW\*(C`WebPage\*(C'\fR classes which both have a \f(CWprint_content()\fR method. This
277 method might produce different output for each class, but they share a
278 common interface.
279 .PP
280 While the two classes may differ in many ways, when it comes to the
281 \&\f(CWprint_content()\fR method, they are the same. This means that we can
282 try to call the \f(CWprint_content()\fR method on an object of either class,
283 and \fBwe don\*(Aqt have to know what class the object belongs to!\fR
284 .PP
285 Polymorphism is one of the key concepts of object\-oriented design.
286 .SS Inheritance
287 .IX Subsection "Inheritance"
288 \&\fBInheritance\fR lets you create a specialized version of an existing
289 class. Inheritance lets the new class reuse the methods and attributes
290 of another class.
291 .PP
292 For example, we could create a \f(CW\*(C`File::MP3\*(C'\fR class which \fBinherits\fR
293 from \f(CW\*(C`File\*(C'\fR. A \f(CW\*(C`File::MP3\*(C'\fR \fBis\-a\fR \fImore specific\fR type of \f(CW\*(C`File\*(C'\fR.
294 All mp3 files are files, but not all files are mp3 files.
295 .PP
296 We often refer to inheritance relationships as \fBparent\-child\fR or
297 \&\f(CW\*(C`superclass\*(C'\fR/\f(CW\*(C`subclass\*(C'\fR relationships. Sometimes we say that the
298 child has an \fBis\-a\fR relationship with its parent class.
299 .PP
300 \&\f(CW\*(C`File\*(C'\fR is a \fBsuperclass\fR of \f(CW\*(C`File::MP3\*(C'\fR, and \f(CW\*(C`File::MP3\*(C'\fR is a
301 \&\fBsubclass\fR of \f(CW\*(C`File\*(C'\fR.
302 .PP
303 .Vb 1
304 \& package File::MP3;
305 \&
306 \& use parent \*(AqFile\*(Aq;
307 .Ve
308 .PP
309 The parent module is one of several ways that Perl lets you define
310 inheritance relationships.
311 .PP
312 Perl allows multiple inheritance, which means that a class can inherit
313 from multiple parents. While this is possible, we strongly recommend
314 against it. Generally, you can use \fBroles\fR to do everything you can do
315 with multiple inheritance, but in a cleaner way.
316 .PP
317 Note that there\*(Aqs nothing wrong with defining multiple subclasses of a
318 given class. This is both common and safe. For example, we might define
319 \&\f(CW\*(C`File::MP3::FixedBitrate\*(C'\fR and \f(CW\*(C`File::MP3::VariableBitrate\*(C'\fR classes to
320 distinguish between different types of mp3 file.
321 .PP
322 \fIOverriding methods and method resolution\fR
323 .IX Subsection "Overriding methods and method resolution"
324 .PP
325 Inheritance allows two classes to share code. By default, every method
326 in the parent class is also available in the child. The child can
327 explicitly \fBoverride\fR a parent\*(Aqs method to provide its own
328 implementation. For example, if we have a \f(CW\*(C`File::MP3\*(C'\fR object, it has
329 the \f(CWprint_info()\fR method from \f(CW\*(C`File\*(C'\fR:
330 .PP
331 .Vb 6
332 \& my $cage = File::MP3\->new(
333 \& path => \*(Aqmp3s/My\-Body\-Is\-a\-Cage.mp3\*(Aq,
334 \& content => $mp3_data,
335 \& last_mod_time => 1304974868,
336 \& title => \*(AqMy Body Is a Cage\*(Aq,
337 \& );
338 \&
339 \& $cage\->print_info;
340 \& # The file is at mp3s/My\-Body\-Is\-a\-Cage.mp3
341 .Ve
342 .PP
343 If we wanted to include the mp3\*(Aqs title in the greeting, we could
344 override the method:
345 .PP
346 .Vb 1
347 \& package File::MP3;
348 \&
349 \& use parent \*(AqFile\*(Aq;
350 \&
351 \& sub print_info {
352 \& my $self = shift;
353 \&
354 \& print "This file is at ", $self\->path, "\en";
355 \& print "Its title is ", $self\->title, "\en";
356 \& }
357 \&
358 \& $cage\->print_info;
359 \& # The file is at mp3s/My\-Body\-Is\-a\-Cage.mp3
360 \& # Its title is My Body Is a Cage
361 .Ve
362 .PP
363 The process of determining what method should be used is called
364 \&\fBmethod resolution\fR. What Perl does is look at the object\*(Aqs class
365 first (\f(CW\*(C`File::MP3\*(C'\fR in this case). If that class defines the method,
366 then that class\*(Aqs version of the method is called. If not, Perl looks
367 at each parent class in turn. For \f(CW\*(C`File::MP3\*(C'\fR, its only parent is
368 \&\f(CW\*(C`File\*(C'\fR. If \f(CW\*(C`File::MP3\*(C'\fR does not define the method, but \f(CW\*(C`File\*(C'\fR does,
369 then Perl calls the method in \f(CW\*(C`File\*(C'\fR.
370 .PP
371 If \f(CW\*(C`File\*(C'\fR inherited from \f(CW\*(C`DataSource\*(C'\fR, which inherited from \f(CW\*(C`Thing\*(C'\fR,
372 then Perl would keep looking "up the chain" if necessary.
373 .PP
374 It is possible to explicitly call a parent method from a child:
375 .PP
376 .Vb 1
377 \& package File::MP3;
378 \&
379 \& use parent \*(AqFile\*(Aq;
380 \&
381 \& sub print_info {
382 \& my $self = shift;
383 \&
384 \& $self\->SUPER::print_info();
385 \& print "Its title is ", $self\->title, "\en";
386 \& }
387 .Ve
388 .PP
389 The \f(CW\*(C`SUPER::\*(C'\fR bit tells Perl to look for the \f(CWprint_info()\fR in the
390 \&\f(CW\*(C`File::MP3\*(C'\fR class\*(Aqs inheritance chain. When it finds the parent class
391 that implements this method, the method is called.
392 .PP
393 We mentioned multiple inheritance earlier. The main problem with
394 multiple inheritance is that it greatly complicates method resolution.
395 See perlobj for more details.
396 .SS Encapsulation
397 .IX Subsection "Encapsulation"
398 \&\fBEncapsulation\fR is the idea that an object is opaque. When another
399 developer uses your class, they don\*(Aqt need to know \fIhow\fR it is
400 implemented, they just need to know \fIwhat\fR it does.
401 .PP
402 Encapsulation is important for several reasons. First, it allows you to
403 separate the public API from the private implementation. This means you
404 can change that implementation without breaking the API.
405 .PP
406 Second, when classes are well encapsulated, they become easier to
407 subclass. Ideally, a subclass uses the same APIs to access object data
408 that its parent class uses. In reality, subclassing sometimes involves
409 violating encapsulation, but a good API can minimize the need to do
410 this.
411 .PP
412 We mentioned earlier that most Perl objects are implemented as hashes
413 under the hood. The principle of encapsulation tells us that we should
414 not rely on this. Instead, we should use accessor methods to access the
415 data in that hash. The object systems that we recommend below all
416 automate the generation of accessor methods. If you use one of them,
417 you should never have to access the object as a hash directly.
418 .SS Composition
419 .IX Subsection "Composition"
420 In object\-oriented code, we often find that one object references
421 another object. This is called \fBcomposition\fR, or a \fBhas\-a\fR
422 relationship.
423 .PP
424 Earlier, we mentioned that the \f(CW\*(C`File\*(C'\fR class\*(Aqs \f(CW\*(C`last_mod_time\*(C'\fR
425 accessor could return a DateTime object. This is a perfect example
426 of composition. We could go even further, and make the \f(CW\*(C`path\*(C'\fR and
427 \&\f(CW\*(C`content\*(C'\fR accessors return objects as well. The \f(CW\*(C`File\*(C'\fR class would
428 then be \fBcomposed\fR of several other objects.
429 .SS Roles
430 .IX Subsection "Roles"
431 \&\fBRoles\fR are something that a class \fIdoes\fR, rather than something that
432 it \fIis\fR. Roles are relatively new to Perl, but have become rather
433 popular. Roles are \fBapplied\fR to classes. Sometimes we say that classes
434 \&\fBconsume\fR roles.
435 .PP
436 Roles are an alternative to inheritance for providing polymorphism.
437 Let\*(Aqs assume we have two classes, \f(CW\*(C`Radio\*(C'\fR and \f(CW\*(C`Computer\*(C'\fR. Both of
438 these things have on/off switches. We want to model that in our class
439 definitions.
440 .PP
441 We could have both classes inherit from a common parent, like
442 \&\f(CW\*(C`Machine\*(C'\fR, but not all machines have on/off switches. We could create
443 a parent class called \f(CW\*(C`HasOnOffSwitch\*(C'\fR, but that is very artificial.
444 Radios and computers are not specializations of this parent. This
445 parent is really a rather ridiculous creation.
446 .PP
447 This is where roles come in. It makes a lot of sense to create a
448 \&\f(CW\*(C`HasOnOffSwitch\*(C'\fR role and apply it to both classes. This role would
449 define a known API like providing \f(CWturn_on()\fR and \f(CWturn_off()\fR
450 methods.
451 .PP
452 Perl does not have any built\-in way to express roles. In the past,
453 people just bit the bullet and used multiple inheritance. Nowadays,
454 there are several good choices on CPAN for using roles.
455 .SS "When to Use OO"
456 .IX Subsection "When to Use OO"
457 Object Orientation is not the best solution to every problem. In \fIPerl
458 Best Practices\fR (copyright 2004, Published by O\*(AqReilly Media, Inc.),
459 Damian Conway provides a list of criteria to use when deciding if OO is
460 the right fit for your problem:
461 .IP \(bu 4
462 The system being designed is large, or is likely to become large.
463 .IP \(bu 4
464 The data can be aggregated into obvious structures, especially if
465 there\*(Aqs a large amount of data in each aggregate.
466 .IP \(bu 4
467 The various types of data aggregate form a natural hierarchy that
468 facilitates the use of inheritance and polymorphism.
469 .IP \(bu 4
470 You have a piece of data on which many different operations are
471 applied.
472 .IP \(bu 4
473 You need to perform the same general operations on related types of
474 data, but with slight variations depending on the specific type of data
475 the operations are applied to.
476 .IP \(bu 4
477 It\*(Aqs likely you\*(Aqll have to add new data types later.
478 .IP \(bu 4
479 The typical interactions between pieces of data are best represented by
480 operators.
481 .IP \(bu 4
482 The implementation of individual components of the system is likely to
483 change over time.
484 .IP \(bu 4
485 The system design is already object\-oriented.
486 .IP \(bu 4
487 Large numbers of other programmers will be using your code modules.
488 .SH "PERL OO SYSTEMS"
489 .IX Header "PERL OO SYSTEMS"
490 As we mentioned before, Perl\*(Aqs built\-in OO system is very minimal, but
491 also quite flexible. Over the years, many people have developed systems
492 which build on top of Perl\*(Aqs built\-in system to provide more features
493 and convenience.
494 .PP
495 We strongly recommend that you use one of these systems. Even the most
496 minimal of them eliminates a lot of repetitive boilerplate. There\*(Aqs
497 really no good reason to write your classes from scratch in Perl.
498 .PP
499 If you are interested in the guts underlying these systems, check out
500 perlobj.
501 .SS Moose
502 .IX Subsection "Moose"
503 Moose bills itself as a "postmodern object system for Perl 5". Don\*(Aqt
504 be scared, the "postmodern" label is a callback to Larry\*(Aqs description
505 of Perl as "the first postmodern computer language".
506 .PP
507 \&\f(CW\*(C`Moose\*(C'\fR provides a complete, modern OO system. Its biggest influence
508 is the Common Lisp Object System, but it also borrows ideas from
509 Smalltalk and several other languages. \f(CW\*(C`Moose\*(C'\fR was created by Stevan
510 Little, and draws heavily from his work on the Raku OO design.
511 .PP
512 Here is our \f(CW\*(C`File\*(C'\fR class using \f(CW\*(C`Moose\*(C'\fR:
513 .PP
514 .Vb 2
515 \& package File;
516 \& use Moose;
517 \&
518 \& has path => ( is => \*(Aqro\*(Aq );
519 \& has content => ( is => \*(Aqro\*(Aq );
520 \& has last_mod_time => ( is => \*(Aqro\*(Aq );
521 \&
522 \& sub print_info {
523 \& my $self = shift;
524 \&
525 \& print "This file is at ", $self\->path, "\en";
526 \& }
527 .Ve
528 .PP
529 \&\f(CW\*(C`Moose\*(C'\fR provides a number of features:
530 .IP \(bu 4
531 Declarative sugar
532 .Sp
533 \&\f(CW\*(C`Moose\*(C'\fR provides a layer of declarative "sugar" for defining classes.
534 That sugar is just a set of exported functions that make declaring how
535 your class works simpler and more palatable. This lets you describe
536 \&\fIwhat\fR your class is, rather than having to tell Perl \fIhow\fR to
537 implement your class.
538 .Sp
539 The \f(CWhas()\fR subroutine declares an attribute, and \f(CW\*(C`Moose\*(C'\fR
540 automatically creates accessors for these attributes. It also takes
541 care of creating a \f(CWnew()\fR method for you. This constructor knows
542 about the attributes you declared, so you can set them when creating a
543 new \f(CW\*(C`File\*(C'\fR.
544 .IP \(bu 4
545 Roles built\-in
546 .Sp
547 \&\f(CW\*(C`Moose\*(C'\fR lets you define roles the same way you define classes:
548 .Sp
549 .Vb 2
550 \& package HasOnOffSwitch;
551 \& use Moose::Role;
552 \&
553 \& has is_on => (
554 \& is => \*(Aqrw\*(Aq,
555 \& isa => \*(AqBool\*(Aq,
556 \& );
557 \&
558 \& sub turn_on {
559 \& my $self = shift;
560 \& $self\->is_on(1);
561 \& }
562 \&
563 \& sub turn_off {
564 \& my $self = shift;
565 \& $self\->is_on(0);
566 \& }
567 .Ve
568 .IP \(bu 4
569 A miniature type system
570 .Sp
571 In the example above, you can see that we passed \f(CW\*(C`isa => \*(AqBool\*(Aq\*(C'\fR
572 to \f(CWhas()\fR when creating our \f(CW\*(C`is_on\*(C'\fR attribute. This tells \f(CW\*(C`Moose\*(C'\fR
573 that this attribute must be a boolean value. If we try to set it to an
574 invalid value, our code will throw an error.
575 .IP \(bu 4
576 Full introspection and manipulation
577 .Sp
578 Perl\*(Aqs built\-in introspection features are fairly minimal. \f(CW\*(C`Moose\*(C'\fR
579 builds on top of them and creates a full introspection layer for your
580 classes. This lets you ask questions like "what methods does the File
581 class implement?" It also lets you modify your classes
582 programmatically.
583 .IP \(bu 4
584 Self\-hosted and extensible
585 .Sp
586 \&\f(CW\*(C`Moose\*(C'\fR describes itself using its own introspection API. Besides
587 being a cool trick, this means that you can extend \f(CW\*(C`Moose\*(C'\fR using
588 \&\f(CW\*(C`Moose\*(C'\fR itself.
589 .IP \(bu 4
590 Rich ecosystem
591 .Sp
592 There is a rich ecosystem of \f(CW\*(C`Moose\*(C'\fR extensions on CPAN under the
593 MooseX <https://metacpan.org/search?q=MooseX>
594 namespace. In addition, many modules on CPAN already use \f(CW\*(C`Moose\*(C'\fR,
595 providing you with lots of examples to learn from.
596 .IP \(bu 4
597 Many more features
598 .Sp
599 \&\f(CW\*(C`Moose\*(C'\fR is a very powerful tool, and we can\*(Aqt cover all of its
600 features here. We encourage you to learn more by reading the \f(CW\*(C`Moose\*(C'\fR
601 documentation, starting with
602 Moose::Manual <https://metacpan.org/pod/Moose::Manual>.
603 .PP
604 Of course, \f(CW\*(C`Moose\*(C'\fR isn\*(Aqt perfect.
605 .PP
606 \&\f(CW\*(C`Moose\*(C'\fR can make your code slower to load. \f(CW\*(C`Moose\*(C'\fR itself is not
607 small, and it does a \fIlot\fR of code generation when you define your
608 class. This code generation means that your runtime code is as fast as
609 it can be, but you pay for this when your modules are first loaded.
610 .PP
611 This load time hit can be a problem when startup speed is important,
612 such as with a command\-line script or a "plain vanilla" CGI script that
613 must be loaded each time it is executed.
614 .PP
615 Before you panic, know that many people do use \f(CW\*(C`Moose\*(C'\fR for
616 command\-line tools and other startup\-sensitive code. We encourage you
617 to try \f(CW\*(C`Moose\*(C'\fR out first before worrying about startup speed.
618 .PP
619 \&\f(CW\*(C`Moose\*(C'\fR also has several dependencies on other modules. Most of these
620 are small stand\-alone modules, a number of which have been spun off
621 from \f(CW\*(C`Moose\*(C'\fR. \f(CW\*(C`Moose\*(C'\fR itself, and some of its dependencies, require a
622 compiler. If you need to install your software on a system without a
623 compiler, or if having \fIany\fR dependencies is a problem, then \f(CW\*(C`Moose\*(C'\fR
624 may not be right for you.
625 .PP
626 \fIMoo\fR
627 .IX Subsection "Moo"
628 .PP
629 If you try \f(CW\*(C`Moose\*(C'\fR and find that one of these issues is preventing you
630 from using \f(CW\*(C`Moose\*(C'\fR, we encourage you to consider Moo next. \f(CW\*(C`Moo\*(C'\fR
631 implements a subset of \f(CW\*(C`Moose\*(C'\fR\*(Aqs functionality in a simpler package.
632 For most features that it does implement, the end\-user API is
633 \&\fIidentical\fR to \f(CW\*(C`Moose\*(C'\fR, meaning you can switch from \f(CW\*(C`Moo\*(C'\fR to
634 \&\f(CW\*(C`Moose\*(C'\fR quite easily.
635 .PP
636 \&\f(CW\*(C`Moo\*(C'\fR does not implement most of \f(CW\*(C`Moose\*(C'\fR\*(Aqs introspection API, so it\*(Aqs
637 often faster when loading your modules. Additionally, none of its
638 dependencies require XS, so it can be installed on machines without a
639 compiler.
640 .PP
641 One of \f(CW\*(C`Moo\*(C'\fR\*(Aqs most compelling features is its interoperability with
642 \&\f(CW\*(C`Moose\*(C'\fR. When someone tries to use \f(CW\*(C`Moose\*(C'\fR\*(Aqs introspection API on a
643 \&\f(CW\*(C`Moo\*(C'\fR class or role, it is transparently inflated into a \f(CW\*(C`Moose\*(C'\fR
644 class or role. This makes it easier to incorporate \f(CW\*(C`Moo\*(C'\fR\-using code
645 into a \f(CW\*(C`Moose\*(C'\fR code base and vice versa.
646 .PP
647 For example, a \f(CW\*(C`Moose\*(C'\fR class can subclass a \f(CW\*(C`Moo\*(C'\fR class using
648 \&\f(CW\*(C`extends\*(C'\fR or consume a \f(CW\*(C`Moo\*(C'\fR role using \f(CW\*(C`with\*(C'\fR.
649 .PP
650 The \f(CW\*(C`Moose\*(C'\fR authors hope that one day \f(CW\*(C`Moo\*(C'\fR can be made obsolete by
651 improving \f(CW\*(C`Moose\*(C'\fR enough, but for now it provides a worthwhile
652 alternative to \f(CW\*(C`Moose\*(C'\fR.
653 .SS Class::Accessor
654 .IX Subsection "Class::Accessor"
655 Class::Accessor is the polar opposite of \f(CW\*(C`Moose\*(C'\fR. It provides very
656 few features, nor is it self\-hosting.
657 .PP
658 It is, however, very simple, pure Perl, and it has no non\-core
659 dependencies. It also provides a "Moose\-like" API on demand for the
660 features it supports.
661 .PP
662 Even though it doesn\*(Aqt do much, it is still preferable to writing your
663 own classes from scratch.
664 .PP
665 Here\*(Aqs our \f(CW\*(C`File\*(C'\fR class with \f(CW\*(C`Class::Accessor\*(C'\fR:
666 .PP
667 .Vb 2
668 \& package File;
669 \& use Class::Accessor \*(Aqantlers\*(Aq;
670 \&
671 \& has path => ( is => \*(Aqro\*(Aq );
672 \& has content => ( is => \*(Aqro\*(Aq );
673 \& has last_mod_time => ( is => \*(Aqro\*(Aq );
674 \&
675 \& sub print_info {
676 \& my $self = shift;
677 \&
678 \& print "This file is at ", $self\->path, "\en";
679 \& }
680 .Ve
681 .PP
682 The \f(CW\*(C`antlers\*(C'\fR import flag tells \f(CW\*(C`Class::Accessor\*(C'\fR that you want to
683 define your attributes using \f(CW\*(C`Moose\*(C'\fR\-like syntax. The only parameter
684 that you can pass to \f(CW\*(C`has\*(C'\fR is \f(CW\*(C`is\*(C'\fR. We recommend that you use this
685 Moose\-like syntax if you choose \f(CW\*(C`Class::Accessor\*(C'\fR since it means you
686 will have a smoother upgrade path if you later decide to move to
687 \&\f(CW\*(C`Moose\*(C'\fR.
688 .PP
689 Like \f(CW\*(C`Moose\*(C'\fR, \f(CW\*(C`Class::Accessor\*(C'\fR generates accessor methods and a
690 constructor for your class.
691 .SS Class::Tiny
692 .IX Subsection "Class::Tiny"
693 Finally, we have Class::Tiny. This module truly lives up to its
694 name. It has an incredibly minimal API and absolutely no dependencies
695 on any recent Perl. Still, we think it\*(Aqs a lot easier to use than
696 writing your own OO code from scratch.
697 .PP
698 Here\*(Aqs our \f(CW\*(C`File\*(C'\fR class once more:
699 .PP
700 .Vb 2
701 \& package File;
702 \& use Class::Tiny qw( path content last_mod_time );
703 \&
704 \& sub print_info {
705 \& my $self = shift;
706 \&
707 \& print "This file is at ", $self\->path, "\en";
708 \& }
709 .Ve
710 .PP
711 That\*(Aqs it!
712 .PP
713 With \f(CW\*(C`Class::Tiny\*(C'\fR, all accessors are read\-write. It generates a
714 constructor for you, as well as the accessors you define.
715 .PP
716 You can also use Class::Tiny::Antlers for \f(CW\*(C`Moose\*(C'\fR\-like syntax.
717 .SS Role::Tiny
718 .IX Subsection "Role::Tiny"
719 As we mentioned before, roles provide an alternative to inheritance,
720 but Perl does not have any built\-in role support. If you choose to use
721 Moose, it comes with a full\-fledged role implementation. However, if
722 you use one of our other recommended OO modules, you can still use
723 roles with Role::Tiny.
724 .PP
725 \&\f(CW\*(C`Role::Tiny\*(C'\fR provides some of the same features as Moose\*(Aqs role
726 system, but in a much smaller package. Most notably, it doesn\*(Aqt support
727 any sort of attribute declaration, so you have to do that by hand.
728 Still, it\*(Aqs useful, and works well with \f(CW\*(C`Class::Accessor\*(C'\fR and
729 \&\f(CW\*(C`Class::Tiny\*(C'\fR.
730 .SS "OO System Summary"
731 .IX Subsection "OO System Summary"
732 Here\*(Aqs a brief recap of the options we covered:
733 .IP \(bu 4
734 Moose
735 .Sp
736 \&\f(CW\*(C`Moose\*(C'\fR is the maximal option. It has a lot of features, a big
737 ecosystem, and a thriving user base. We also covered Moo briefly.
738 \&\f(CW\*(C`Moo\*(C'\fR is \f(CW\*(C`Moose\*(C'\fR lite, and a reasonable alternative when Moose
739 doesn\*(Aqt work for your application.
740 .IP \(bu 4
741 Class::Accessor
742 .Sp
743 \&\f(CW\*(C`Class::Accessor\*(C'\fR does a lot less than \f(CW\*(C`Moose\*(C'\fR, and is a nice
744 alternative if you find \f(CW\*(C`Moose\*(C'\fR overwhelming. It\*(Aqs been around a long
745 time and is well battle\-tested. It also has a minimal \f(CW\*(C`Moose\*(C'\fR
746 compatibility mode which makes moving from \f(CW\*(C`Class::Accessor\*(C'\fR to
747 \&\f(CW\*(C`Moose\*(C'\fR easy.
748 .IP \(bu 4
749 Class::Tiny
750 .Sp
751 \&\f(CW\*(C`Class::Tiny\*(C'\fR is the absolute minimal option. It has no dependencies,
752 and almost no syntax to learn. It\*(Aqs a good option for a super minimal
753 environment and for throwing something together quickly without having
754 to worry about details.
755 .IP \(bu 4
756 Role::Tiny
757 .Sp
758 Use \f(CW\*(C`Role::Tiny\*(C'\fR with \f(CW\*(C`Class::Accessor\*(C'\fR or \f(CW\*(C`Class::Tiny\*(C'\fR if you find
759 yourself considering multiple inheritance. If you go with \f(CW\*(C`Moose\*(C'\fR, it
760 comes with its own role implementation.
761 .SS "Other OO Systems"
762 .IX Subsection "Other OO Systems"
763 There are literally dozens of other OO\-related modules on CPAN besides
764 those covered here, and you\*(Aqre likely to run across one or more of them
765 if you work with other people\*(Aqs code.
766 .PP
767 In addition, plenty of code in the wild does all of its OO "by hand",
768 using just the Perl built\-in OO features. If you need to maintain such
769 code, you should read perlobj to understand exactly how Perl\*(Aqs
770 built\-in OO works.
771 .SH CONCLUSION
772 .IX Header "CONCLUSION"
773 As we said before, Perl\*(Aqs minimal OO system has led to a profusion of
774 OO systems on CPAN. While you can still drop down to the bare metal and
775 write your classes by hand, there\*(Aqs really no reason to do that with
776 modern Perl.
777 .PP
778 For small systems, Class::Tiny and Class::Accessor both provide
779 minimal object systems that take care of basic boilerplate for you.
780 .PP
781 For bigger projects, Moose provides a rich set of features that will
782 let you focus on implementing your business logic. Moo provides a
783 nice alternative to Moose when you want a lot of features but need
784 faster compile time or to avoid XS.
785 .PP
786 We encourage you to play with and evaluate Moose, Moo,
787 Class::Accessor, and Class::Tiny to see which OO system is right
788 for you.