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