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