Debian Codegraph @

upstream/fedora-44/man1/perlobj.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 "PERLOBJ 1"
61 .TH PERLOBJ 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 perlobj \- Perl object reference
68 .IX Xref "object OOP"
69 .SH DESCRIPTION
70 .IX Header "DESCRIPTION"
71 This document provides a reference for Perl\*(Aqs object orientation
72 features. If you\*(Aqre looking for an introduction to object\-oriented
73 programming in Perl, please see perlootut.
74 .PP
75 In order to understand Perl objects, you first need to understand
76 references in Perl. See perlreftut for details.
77 .PP
78 This document describes all of Perl\*(Aqs object\-oriented (OO) features
79 from the ground up. If you\*(Aqre just looking to write some
80 object\-oriented code of your own, you are probably better served by
81 using one of the object systems from CPAN described in perlootut.
82 .PP
83 If you\*(Aqre looking to write your own object system, or you need to
84 maintain code which implements objects from scratch then this document
85 will help you understand exactly how Perl does object orientation.
86 .PP
87 There are a few basic principles which define object oriented Perl:
88 .IP 1. 4
89 An object is simply a data structure that knows to which class it
90 belongs.
91 .IP 2. 4
92 A class is simply a package. A class provides methods that expect to
93 operate on objects.
94 .IP 3. 4
95 A method is simply a subroutine that expects a reference to an object
96 (or a package name, for class methods) as the first argument.
97 .PP
98 Let\*(Aqs look at each of these principles in depth.
99 .SS "An Object is Simply a Data Structure"
100 .IX Xref "object bless constructor new"
101 .IX Subsection "An Object is Simply a Data Structure"
102 Unlike many other languages which support object orientation, Perl does
103 not provide any special syntax for constructing an object. Objects are
104 merely Perl data structures (hashes, arrays, scalars, filehandles,
105 etc.) that have been explicitly associated with a particular class.
106 .PP
107 That explicit association is created by the built\-in \f(CW\*(C`bless\*(C'\fR function,
108 which is typically used within the \fIconstructor\fR subroutine of the
109 class.
110 .PP
111 Here is a simple constructor:
112 .PP
113 .Vb 1
114 \& package File;
115 \&
116 \& sub new {
117 \& my $class = shift;
118 \&
119 \& return bless {}, $class;
120 \& }
121 .Ve
122 .PP
123 The name \f(CW\*(C`new\*(C'\fR isn\*(Aqt special. We could name our constructor something
124 else:
125 .PP
126 .Vb 1
127 \& package File;
128 \&
129 \& sub load {
130 \& my $class = shift;
131 \&
132 \& return bless {}, $class;
133 \& }
134 .Ve
135 .PP
136 The modern convention for OO modules is to always use \f(CW\*(C`new\*(C'\fR as the
137 name for the constructor, but there is no requirement to do so. Any
138 subroutine that blesses a data structure into a class is a valid
139 constructor in Perl.
140 .PP
141 In the previous examples, the \f(CW\*(C`{}\*(C'\fR code creates a reference to an
142 empty anonymous hash. The \f(CW\*(C`bless\*(C'\fR function then takes that reference
143 and associates the hash with the class in \f(CW$class\fR. In the simplest
144 case, the \f(CW$class\fR variable will end up containing the string "File".
145 .PP
146 We can also use a variable to store a reference to the data structure
147 that is being blessed as our object:
148 .PP
149 .Vb 2
150 \& sub new {
151 \& my $class = shift;
152 \&
153 \& my $self = {};
154 \& bless $self, $class;
155 \&
156 \& return $self;
157 \& }
158 .Ve
159 .PP
160 Once we\*(Aqve blessed the hash referred to by \f(CW$self\fR we can start
161 calling methods on it. This is useful if you want to put object
162 initialization in its own separate method:
163 .PP
164 .Vb 2
165 \& sub new {
166 \& my $class = shift;
167 \&
168 \& my $self = {};
169 \& bless $self, $class;
170 \&
171 \& $self\->_initialize();
172 \&
173 \& return $self;
174 \& }
175 .Ve
176 .PP
177 Since the object is also a hash, you can treat it as one, using it to
178 store data associated with the object. Typically, code inside the class
179 can treat the hash as an accessible data structure, while code outside
180 the class should always treat the object as opaque. This is called
181 \&\fBencapsulation\fR. Encapsulation means that the user of an object does
182 not have to know how it is implemented. The user simply calls
183 documented methods on the object.
184 .PP
185 Note, however, that (unlike most other OO languages) Perl does not
186 ensure or enforce encapsulation in any way. If you want objects to
187 actually \fIbe\fR opaque you need to arrange for that yourself. This can
188 be done in a variety of ways, including using "Inside\-Out objects"
189 or modules from CPAN.
190 .PP
191 \fIObjects Are Blessed; Variables Are Not\fR
192 .IX Subsection "Objects Are Blessed; Variables Are Not"
193 .PP
194 When we bless something, we are not blessing the variable which
195 contains a reference to that thing, nor are we blessing the reference
196 that the variable stores; we are blessing the thing that the variable
197 refers to (sometimes known as the \fIreferent\fR). This is best
198 demonstrated with this code:
199 .PP
200 .Vb 1
201 \& use Scalar::Util \*(Aqblessed\*(Aq;
202 \&
203 \& my $foo = {};
204 \& my $bar = $foo;
205 \&
206 \& bless $foo, \*(AqClass\*(Aq;
207 \& print blessed( $bar ) // \*(Aqnot blessed\*(Aq; # prints "Class"
208 \&
209 \& $bar = "some other value";
210 \& print blessed( $bar ) // \*(Aqnot blessed\*(Aq; # prints "not blessed"
211 .Ve
212 .PP
213 When we call \f(CW\*(C`bless\*(C'\fR on a variable, we are actually blessing the
214 underlying data structure that the variable refers to. We are not
215 blessing the reference itself, nor the variable that contains that
216 reference. That\*(Aqs why the second call to \f(CWblessed( $bar )\fR returns
217 false. At that point \f(CW$bar\fR is no longer storing a reference to an
218 object.
219 .PP
220 You will sometimes see older books or documentation mention "blessing a
221 reference" or describe an object as a "blessed reference", but this is
222 incorrect. It isn\*(Aqt the reference that is blessed as an object; it\*(Aqs
223 the thing the reference refers to (\fIi.e.\fR, the referent).
224 .SS "A Class is Simply a Package"
225 .IX Xref "class package @ISA inheritance"
226 .IX Subsection "A Class is Simply a Package"
227 Perl does not provide any special syntax for class definitions. A
228 package is simply a namespace containing variables and subroutines. The
229 only difference is that in a class, the subroutines may expect a
230 reference to an object or the name of a class as the first argument.
231 This is purely a matter of convention, so a class may contain both
232 methods and subroutines which \fIdon\*(Aqt\fR operate on an object or class.
233 .PP
234 Each package contains a special array called \f(CW@ISA\fR. The \f(CW@ISA\fR array
235 contains a list of that class\*(Aqs parent classes, if any. This array is
236 examined when Perl does method resolution, which we will cover later.
237 .PP
238 Calling methods from a package means it must be loaded, of course, so
239 you will often want to load a module and add it to \f(CW@ISA\fR at the same
240 time. You can do so in a single step using the parent pragma.
241 (In older code you may encounter the base pragma, which is nowadays
242 discouraged except when you have to work with the equally discouraged
243 fields pragma.)
244 .PP
245 However the parent classes are set, the package\*(Aqs \f(CW@ISA\fR variable will
246 contain a list of those parents. This is simply a list of scalars, each
247 of which is a string that corresponds to a package name.
248 .PP
249 All classes inherit from the UNIVERSAL class implicitly. The
250 UNIVERSAL class is implemented by the Perl core, and provides
251 several default methods, such as \f(CWisa()\fR, \f(CWcan()\fR, and \f(CWVERSION()\fR.
252 The \f(CW\*(C`UNIVERSAL\*(C'\fR class will \fInever\fR appear in a package\*(Aqs \f(CW@ISA\fR
253 variable.
254 .PP
255 Perl \fIonly\fR provides method inheritance as a built\-in feature.
256 Attribute inheritance is left up the class to implement. See the
257 "Writing Accessors" section for details.
258 .SS "A Method is Simply a Subroutine"
259 .IX Xref "method"
260 .IX Subsection "A Method is Simply a Subroutine"
261 Perl does not provide any special syntax for defining a method. A
262 method is simply a regular subroutine, and is declared with \f(CW\*(C`sub\*(C'\fR.
263 What makes a method special is that it expects to receive either an
264 object or a class name as its first argument.
265 .PP
266 Perl \fIdoes\fR provide special syntax for method invocation, the \f(CW\*(C`\->\*(C'\fR operator. We will cover this in more detail later.
267 .PP
268 Most methods you write will expect to operate on objects:
269 .PP
270 .Vb 2
271 \& sub save {
272 \& my $self = shift;
273 \&
274 \& open my $fh, \*(Aq>\*(Aq, $self\->path() or die $!;
275 \& print {$fh} $self\->data() or die $!;
276 \& close $fh or die $!;
277 \& }
278 .Ve
279 .SS "Method Invocation"
280 .IX Xref "invocation method arrow ->"
281 .IX Subsection "Method Invocation"
282 Calling a method on an object is written as \f(CW\*(C`$object\->method\*(C'\fR.
283 .PP
284 The left hand side of the method invocation (or arrow) operator is the
285 object (or class name), and the right hand side is the method name.
286 .PP
287 .Vb 2
288 \& my $pod = File\->new( \*(Aqperlobj.pod\*(Aq, $data );
289 \& $pod\->save();
290 .Ve
291 .PP
292 The \f(CW\*(C`\->\*(C'\fR syntax is also used when dereferencing a reference. It
293 looks like the same operator, but these are two different operations.
294 .PP
295 When you call a method, the thing on the left side of the arrow is
296 passed as the first argument to the method. That means when we call \f(CW\*(C`Critter\->new()\*(C'\fR, the \f(CWnew()\fR method receives the string \f(CW"Critter"\fR
297 as its first argument. When we call \f(CW\*(C`$fred\->speak()\*(C'\fR, the \f(CW$fred\fR
298 variable is passed as the first argument to \f(CWspeak()\fR.
299 .PP
300 Just as with any Perl subroutine, all of the arguments passed in \f(CW@_\fR
301 are aliases to the original argument. This includes the object itself.
302 If you assign directly to \f(CW$_[0]\fR you will change the contents of the
303 variable that holds the reference to the object. We recommend that you
304 don\*(Aqt do this unless you know exactly what you\*(Aqre doing.
305 .PP
306 Perl knows what package the method is in by looking at the left side of
307 the arrow. If the left hand side is a package name, it looks for the
308 method in that package. If the left hand side is an object, then Perl
309 looks for the method in the package that the object has been blessed
310 into.
311 .PP
312 If the left hand side is neither a package name nor an object, then the
313 method call will cause an error, but see the section on "Method Call
314 Variations" for more nuances.
315 .SS Inheritance
316 .IX Xref "inheritance"
317 .IX Subsection "Inheritance"
318 We already talked about the special \f(CW@ISA\fR array and the parent
319 pragma.
320 .PP
321 When a class inherits from another class, any methods defined in the
322 parent class are available to the child class. If you attempt to call a
323 method on an object that isn\*(Aqt defined in its own class, Perl will also
324 look for that method in any parent classes it may have.
325 .PP
326 .Vb 2
327 \& package File::MP3;
328 \& use parent \*(AqFile\*(Aq; # sets @File::MP3::ISA = (\*(AqFile\*(Aq);
329 \&
330 \& my $mp3 = File::MP3\->new( \*(AqAndvari.mp3\*(Aq, $data );
331 \& $mp3\->save();
332 .Ve
333 .PP
334 Since we didn\*(Aqt define a \f(CWsave()\fR method in the \f(CW\*(C`File::MP3\*(C'\fR class,
335 Perl will look at the \f(CW\*(C`File::MP3\*(C'\fR class\*(Aqs parent classes to find the
336 \&\f(CWsave()\fR method. If Perl cannot find a \f(CWsave()\fR method anywhere in
337 the inheritance hierarchy, it will die.
338 .PP
339 In this case, it finds a \f(CWsave()\fR method in the \f(CW\*(C`File\*(C'\fR class. Note
340 that the object passed to \f(CWsave()\fR in this case is still a
341 \&\f(CW\*(C`File::MP3\*(C'\fR object, even though the method is found in the \f(CW\*(C`File\*(C'\fR
342 class.
343 .PP
344 We can override a parent\*(Aqs method in a child class. When we do so, we
345 can still call the parent class\*(Aqs method with the \f(CW\*(C`SUPER\*(C'\fR
346 pseudo\-class.
347 .PP
348 .Vb 2
349 \& sub save {
350 \& my $self = shift;
351 \&
352 \& say \*(AqPrepare to rock\*(Aq;
353 \& $self\->SUPER::save();
354 \& }
355 .Ve
356 .PP
357 The \f(CW\*(C`SUPER\*(C'\fR modifier can \fIonly\fR be used for method calls. You can\*(Aqt
358 use it for regular subroutine calls or class methods:
359 .PP
360 .Vb 1
361 \& SUPER::save($thing); # FAIL: looks for save() sub in package SUPER
362 \&
363 \& SUPER\->save($thing); # FAIL: looks for save() method in class
364 \& # SUPER
365 \&
366 \& $thing\->SUPER::save(); # Okay: looks for save() method in parent
367 \& # classes
368 .Ve
369 .PP
370 \fIHow SUPER is Resolved\fR
371 .IX Xref "SUPER"
372 .IX Subsection "How SUPER is Resolved"
373 .PP
374 The \f(CW\*(C`SUPER\*(C'\fR pseudo\-class is resolved from the package where the call
375 is made. It is \fInot\fR resolved based on the object\*(Aqs class. This is
376 important, because it lets methods at different levels within a deep
377 inheritance hierarchy each correctly call their respective parent
378 methods.
379 .PP
380 .Vb 1
381 \& package A;
382 \&
383 \& sub new {
384 \& return bless {}, shift;
385 \& }
386 \&
387 \& sub speak {
388 \& my $self = shift;
389 \&
390 \& say \*(AqA\*(Aq;
391 \& }
392 \&
393 \& package B;
394 \&
395 \& use parent \-norequire, \*(AqA\*(Aq;
396 \&
397 \& sub speak {
398 \& my $self = shift;
399 \&
400 \& $self\->SUPER::speak();
401 \&
402 \& say \*(AqB\*(Aq;
403 \& }
404 \&
405 \& package C;
406 \&
407 \& use parent \-norequire, \*(AqB\*(Aq;
408 \&
409 \& sub speak {
410 \& my $self = shift;
411 \&
412 \& $self\->SUPER::speak();
413 \&
414 \& say \*(AqC\*(Aq;
415 \& }
416 \&
417 \& my $c = C\->new();
418 \& $c\->speak();
419 .Ve
420 .PP
421 In this example, we will get the following output:
422 .PP
423 .Vb 3
424 \& A
425 \& B
426 \& C
427 .Ve
428 .PP
429 This demonstrates how \f(CW\*(C`SUPER\*(C'\fR is resolved. Even though the object is
430 blessed into the \f(CW\*(C`C\*(C'\fR class, the \f(CWspeak()\fR method in the \f(CW\*(C`B\*(C'\fR class
431 can still call \f(CWSUPER::speak()\fR and expect it to correctly look in the
432 parent class of \f(CW\*(C`B\*(C'\fR (\fIi.e.\fR, the class the method call is in), not in the
433 parent class of \f(CW\*(C`C\*(C'\fR (i.e. the class the object belongs to).
434 .PP
435 There are rare cases where this package\-based resolution can be a
436 problem. If you copy a subroutine from one package to another, \f(CW\*(C`SUPER\*(C'\fR
437 resolution will be done based on the original package.
438 .PP
439 \fIMultiple Inheritance\fR
440 .IX Xref "multiple inheritance"
441 .IX Subsection "Multiple Inheritance"
442 .PP
443 Multiple inheritance often indicates a design problem, but Perl always
444 gives you enough rope to hang yourself with if you ask for it.
445 .PP
446 To declare multiple parents, you simply need to pass multiple class
447 names to \f(CW\*(C`use parent\*(C'\fR:
448 .PP
449 .Vb 1
450 \& package MultiChild;
451 \&
452 \& use parent \*(AqParent1\*(Aq, \*(AqParent2\*(Aq;
453 .Ve
454 .PP
455 \fIMethod Resolution Order\fR
456 .IX Xref "method resolution order mro"
457 .IX Subsection "Method Resolution Order"
458 .PP
459 Method resolution order only matters in the case of multiple
460 inheritance. In the case of single inheritance, Perl simply looks up
461 the inheritance chain to find a method:
462 .PP
463 .Vb 5
464 \& Grandparent
465 \& |
466 \& Parent
467 \& |
468 \& Child
469 .Ve
470 .PP
471 If we call a method on a \f(CW\*(C`Child\*(C'\fR object and that method is not defined
472 in the \f(CW\*(C`Child\*(C'\fR class, Perl will look for that method in the \f(CW\*(C`Parent\*(C'\fR
473 class and then, if necessary, in the \f(CW\*(C`Grandparent\*(C'\fR class.
474 .PP
475 If Perl cannot find the method in any of these classes, it will die
476 with an error message.
477 .PP
478 When a class has multiple parents, the method lookup order becomes more
479 complicated.
480 .PP
481 By default, Perl does a depth\-first left\-to\-right search for a method.
482 That means it starts with the first parent in the \f(CW@ISA\fR array, and
483 then searches all of its parents, grandparents, etc. If it fails to
484 find the method, it then goes to the next parent in the original
485 class\*(Aqs \f(CW@ISA\fR array and searches from there.
486 .PP
487 .Vb 7
488 \& SharedGreatGrandParent
489 \& / \e
490 \& PaternalGrandparent MaternalGrandparent
491 \& \e /
492 \& Father Mother
493 \& \e /
494 \& Child
495 .Ve
496 .PP
497 So given the diagram above, Perl will search \f(CW\*(C`Child\*(C'\fR, \f(CW\*(C`Father\*(C'\fR,
498 \&\f(CW\*(C`PaternalGrandparent\*(C'\fR, \f(CW\*(C`SharedGreatGrandParent\*(C'\fR, \f(CW\*(C`Mother\*(C'\fR, and
499 finally \f(CW\*(C`MaternalGrandparent\*(C'\fR. This may be a problem because now we\*(Aqre
500 looking in \f(CW\*(C`SharedGreatGrandParent\*(C'\fR \fIbefore\fR we\*(Aqve checked all its
501 derived classes (i.e. before we tried \f(CW\*(C`Mother\*(C'\fR and
502 \&\f(CW\*(C`MaternalGrandparent\*(C'\fR).
503 .PP
504 It is possible to ask for a different method resolution order with the
505 mro pragma.
506 .PP
507 .Vb 1
508 \& package Child;
509 \&
510 \& use mro \*(Aqc3\*(Aq;
511 \& use parent \*(AqFather\*(Aq, \*(AqMother\*(Aq;
512 .Ve
513 .PP
514 This pragma lets you switch to the "C3" resolution order. In simple
515 terms, "C3" order ensures that shared parent classes are never searched
516 before child classes, so Perl will now search: \f(CW\*(C`Child\*(C'\fR, \f(CW\*(C`Father\*(C'\fR,
517 \&\f(CW\*(C`PaternalGrandparent\*(C'\fR, \f(CW\*(C`Mother\*(C'\fR \f(CW\*(C`MaternalGrandparent\*(C'\fR, and finally
518 \&\f(CW\*(C`SharedGreatGrandParent\*(C'\fR. Note however that this is not
519 "breadth\-first" searching: All the \f(CW\*(C`Father\*(C'\fR ancestors (except the
520 common ancestor) are searched before any of the \f(CW\*(C`Mother\*(C'\fR ancestors are
521 considered.
522 .PP
523 The C3 order also lets you call methods in sibling classes with the
524 \&\f(CW\*(C`next\*(C'\fR pseudo\-class. See the mro documentation for more details on
525 this feature.
526 .PP
527 \fIMethod Resolution Caching\fR
528 .IX Subsection "Method Resolution Caching"
529 .PP
530 When Perl searches for a method, it caches the lookup so that future
531 calls to the method do not need to search for it again. Changing a
532 class\*(Aqs parent class or adding subroutines to a class will invalidate
533 the cache for that class.
534 .PP
535 The mro pragma provides some functions for manipulating the method
536 cache directly.
537 .SS "Writing Constructors"
538 .IX Xref "constructor"
539 .IX Subsection "Writing Constructors"
540 As we mentioned earlier, Perl provides no special constructor syntax.
541 This means that a class must implement its own constructor. A
542 constructor is simply a class method that returns a reference to a new
543 object.
544 .PP
545 The constructor can also accept additional parameters that define the
546 object. Let\*(Aqs write a real constructor for the \f(CW\*(C`File\*(C'\fR class we used
547 earlier:
548 .PP
549 .Vb 1
550 \& package File;
551 \&
552 \& sub new {
553 \& my $class = shift;
554 \& my ( $path, $data ) = @_;
555 \&
556 \& my $self = bless {
557 \& path => $path,
558 \& data => $data,
559 \& }, $class;
560 \&
561 \& return $self;
562 \& }
563 .Ve
564 .PP
565 As you can see, we\*(Aqve stored the path and file data in the object
566 itself. Remember, under the hood, this object is still just a hash.
567 Later, we\*(Aqll write accessors to manipulate this data.
568 .PP
569 For our \f(CW\*(C`File::MP3\*(C'\fR class, we can check to make sure that the path
570 we\*(Aqre given ends with ".mp3":
571 .PP
572 .Vb 1
573 \& package File::MP3;
574 \&
575 \& sub new {
576 \& my $class = shift;
577 \& my ( $path, $data ) = @_;
578 \&
579 \& die "You cannot create a File::MP3 without an mp3 extension\en"
580 \& unless $path =~ /\e.mp3\ez/;
581 \&
582 \& return $class\->SUPER::new(@_);
583 \& }
584 .Ve
585 .PP
586 This constructor lets its parent class do the actual object
587 construction.
588 .SS Attributes
589 .IX Xref "attribute"
590 .IX Subsection "Attributes"
591 An attribute is a piece of data belonging to a particular object.
592 Unlike most object\-oriented languages, Perl provides no special syntax
593 or support for declaring and manipulating attributes.
594 .PP
595 Attributes are often stored in the object itself. For example, if the
596 object is an anonymous hash, we can store the attribute values in the
597 hash using the attribute name as the key.
598 .PP
599 While it\*(Aqs possible to refer directly to these hash keys outside of the
600 class, it\*(Aqs considered a best practice to wrap all access to the
601 attribute with accessor methods.
602 .PP
603 This has several advantages. Accessors make it easier to change the
604 implementation of an object later while still preserving the original
605 API.
606 .PP
607 An accessor lets you add additional code around attribute access. For
608 example, you could apply a default to an attribute that wasn\*(Aqt set in
609 the constructor, or you could validate that a new value for the
610 attribute is acceptable.
611 .PP
612 Finally, using accessors makes inheritance much simpler. Subclasses can
613 use the accessors rather than having to know how a parent class is
614 implemented internally.
615 .PP
616 \fIWriting Accessors\fR
617 .IX Xref "accessor"
618 .IX Subsection "Writing Accessors"
619 .PP
620 As with constructors, Perl provides no special accessor declaration
621 syntax, so classes must provide explicitly written accessor methods.
622 There are two common types of accessors, read\-only and read\-write.
623 .PP
624 A simple read\-only accessor simply gets the value of a single
625 attribute:
626 .PP
627 .Vb 2
628 \& sub path {
629 \& my $self = shift;
630 \&
631 \& return $self\->{path};
632 \& }
633 .Ve
634 .PP
635 A read\-write accessor will allow the caller to set the value as well as
636 get it:
637 .PP
638 .Vb 2
639 \& sub path {
640 \& my $self = shift;
641 \&
642 \& if (@_) {
643 \& $self\->{path} = shift;
644 \& }
645 \&
646 \& return $self\->{path};
647 \& }
648 .Ve
649 .SS "An Aside About Smarter and Safer Code"
650 .IX Subsection "An Aside About Smarter and Safer Code"
651 Our constructor and accessors are not very smart. They don\*(Aqt check that
652 a \f(CW$path\fR is defined, nor do they check that a \f(CW$path\fR is a valid
653 filesystem path.
654 .PP
655 Doing these checks by hand can quickly become tedious. Writing a bunch
656 of accessors by hand is also incredibly tedious. There are a lot of
657 modules on CPAN that can help you write safer and more concise code,
658 including the modules we recommend in perlootut.
659 .SS "Method Call Variations"
660 .IX Xref "method"
661 .IX Subsection "Method Call Variations"
662 Perl supports several other ways to call methods besides the \f(CW\*(C`$object\->method()\*(C'\fR usage we\*(Aqve seen so far.
663 .PP
664 \fIMethod Names with a Fully Qualified Name\fR
665 .IX Subsection "Method Names with a Fully Qualified Name"
666 .PP
667 Perl allows you to call methods using their fully qualified name (the
668 package and method name):
669 .PP
670 .Vb 2
671 \& my $mp3 = File::MP3\->new( \*(AqRegin.mp3\*(Aq, $data );
672 \& $mp3\->File::save();
673 .Ve
674 .PP
675 When you call a fully qualified method name like \f(CW\*(C`File::save\*(C'\fR, the method
676 resolution search for the \f(CW\*(C`save\*(C'\fR method starts in the \f(CW\*(C`File\*(C'\fR class,
677 skipping any \f(CW\*(C`save\*(C'\fR method the \f(CW\*(C`File::MP3\*(C'\fR class may have defined. It
678 still searches the \f(CW\*(C`File\*(C'\fR class\*(Aqs parents if necessary.
679 .PP
680 While this feature is most commonly used to explicitly call methods
681 inherited from an ancestor class, there is no technical restriction
682 that enforces this:
683 .PP
684 .Vb 2
685 \& my $obj = Tree\->new();
686 \& $obj\->Dog::bark();
687 .Ve
688 .PP
689 This calls the \f(CW\*(C`bark\*(C'\fR method from class \f(CW\*(C`Dog\*(C'\fR on an object of class
690 \&\f(CW\*(C`Tree\*(C'\fR, even if the two classes are completely unrelated. Use this
691 with great care.
692 .PP
693 The \f(CW\*(C`SUPER\*(C'\fR pseudo\-class that was described earlier is \fInot\fR the same
694 as calling a method with a fully\-qualified name. See the earlier
695 "Inheritance" section for details.
696 .PP
697 \fIMethod Names as Strings\fR
698 .IX Subsection "Method Names as Strings"
699 .PP
700 Perl lets you use a scalar variable containing a string as a method
701 name:
702 .PP
703 .Vb 1
704 \& my $file = File\->new( $path, $data );
705 \&
706 \& my $method = \*(Aqsave\*(Aq;
707 \& $file\->$method();
708 .Ve
709 .PP
710 This works exactly like calling \f(CW\*(C`$file\->save()\*(C'\fR. This can be very
711 useful for writing dynamic code. For example, it allows you to pass a
712 method name to be called as a parameter to another method.
713 .PP
714 \fIClass Names as Strings\fR
715 .IX Subsection "Class Names as Strings"
716 .PP
717 Perl also lets you use a scalar containing a string as a class name:
718 .PP
719 .Vb 1
720 \& my $class = \*(AqFile\*(Aq;
721 \&
722 \& my $file = $class\->new( $path, $data );
723 .Ve
724 .PP
725 Again, this allows for very dynamic code.
726 .PP
727 \fISubroutine References as Methods\fR
728 .IX Subsection "Subroutine References as Methods"
729 .PP
730 You can also use a subroutine reference as a method:
731 .PP
732 .Vb 2
733 \& my $sub = sub {
734 \& my $self = shift;
735 \&
736 \& $self\->save();
737 \& };
738 \&
739 \& $file\->$sub();
740 .Ve
741 .PP
742 This is exactly equivalent to writing \f(CW$sub\->($file)\fR. You may see
743 this idiom in the wild combined with a call to \f(CW\*(C`can\*(C'\fR:
744 .PP
745 .Vb 3
746 \& if ( my $meth = $object\->can(\*(Aqfoo\*(Aq) ) {
747 \& $object\->$meth();
748 \& }
749 .Ve
750 .PP
751 \fIDereferencing Method Call\fR
752 .IX Subsection "Dereferencing Method Call"
753 .PP
754 Perl also lets you use a dereferenced scalar reference in a method
755 call. That\*(Aqs a mouthful, so let\*(Aqs look at some code:
756 .PP
757 .Vb 4
758 \& $file\->${ \e\*(Aqsave\*(Aq };
759 \& $file\->${ returns_scalar_ref() };
760 \& $file\->${ \e( returns_scalar() ) };
761 \& $file\->${ returns_ref_to_sub_ref() };
762 .Ve
763 .PP
764 This works if the dereference produces a string \fIor\fR a subroutine
765 reference.
766 .PP
767 \fIMethod Calls on Filehandles\fR
768 .IX Subsection "Method Calls on Filehandles"
769 .PP
770 Under the hood, Perl filehandles are instances of the \f(CW\*(C`IO::Handle\*(C'\fR or
771 \&\f(CW\*(C`IO::File\*(C'\fR class. Once you have an open filehandle, you can call
772 methods on it. Additionally, you can call methods on the \f(CW\*(C`STDIN\*(C'\fR,
773 \&\f(CW\*(C`STDOUT\*(C'\fR, and \f(CW\*(C`STDERR\*(C'\fR filehandles.
774 .PP
775 .Vb 3
776 \& open my $fh, \*(Aq>\*(Aq, \*(Aqpath/to/file\*(Aq;
777 \& $fh\->autoflush();
778 \& $fh\->print(\*(Aqcontent\*(Aq);
779 \&
780 \& STDOUT\->autoflush();
781 .Ve
782 .SS "Invoking Class Methods"
783 .IX Xref "invocation"
784 .IX Subsection "Invoking Class Methods"
785 Because Perl allows you to use barewords for package names and
786 subroutine names, it sometimes interprets a bareword\*(Aqs meaning
787 incorrectly. For example, the construct \f(CW\*(C`Class\->new()\*(C'\fR can be
788 interpreted as either \f(CW\*(C`\*(AqClass\*(Aq\->new()\*(C'\fR or \f(CW\*(C`Class()\->new()\*(C'\fR.
789 In English, that second interpretation reads as "call a subroutine
790 named \fBClass()\fR, then call \fBnew()\fR as a method on the return value of
791 \&\fBClass()\fR". If there is a subroutine named \f(CWClass()\fR in the current
792 namespace, Perl will always interpret \f(CW\*(C`Class\->new()\*(C'\fR as the second
793 alternative: a call to \f(CWnew()\fR on the object returned by a call to
794 \&\f(CWClass()\fR
795 .PP
796 You can force Perl to use the first interpretation (i.e. as a method
797 call on the class named "Class") in two ways. First, you can append a
798 \&\f(CW\*(C`::\*(C'\fR to the class name:
799 .PP
800 .Vb 1
801 \& Class::\->new()
802 .Ve
803 .PP
804 Perl will always interpret this as a method call.
805 .PP
806 Alternatively, you can quote the class name:
807 .PP
808 .Vb 1
809 \& \*(AqClass\*(Aq\->new()
810 .Ve
811 .PP
812 Of course, if the class name is in a scalar Perl will do the right
813 thing as well:
814 .PP
815 .Vb 2
816 \& my $class = \*(AqClass\*(Aq;
817 \& $class\->new();
818 .Ve
819 .PP
820 \fIIndirect Object Syntax\fR
821 .IX Xref "indirect object"
822 .IX Subsection "Indirect Object Syntax"
823 .PP
824 \&\fBOutside of the file handle case, use of this syntax is discouraged as
825 it can confuse the Perl interpreter. See below for more details.\fR
826 .PP
827 Perl supports another method invocation syntax called "indirect object"
828 notation. This syntax is called "indirect" because the method comes
829 before the object it is being invoked on.
830 .PP
831 This syntax can be used with any class or object method:
832 .PP
833 .Vb 2
834 \& my $file = new File $path, $data;
835 \& save $file;
836 .Ve
837 .PP
838 We recommend that you avoid this syntax, for several reasons.
839 .PP
840 First, it can be confusing to read. In the above example, it\*(Aqs not
841 clear if \f(CW\*(C`save\*(C'\fR is a method provided by the \f(CW\*(C`File\*(C'\fR class or simply a
842 subroutine that expects a file object as its first argument.
843 .PP
844 When used with class methods, the problem is even worse. Because Perl
845 allows subroutine names to be written as barewords, Perl has to guess
846 whether the bareword after the method is a class name or subroutine
847 name. In other words, Perl can resolve the syntax as either \f(CW\*(C`File\->new( $path, $data )\*(C'\fR \fBor\fR \f(CW\*(C`new( File( $path, $data ) )\*(C'\fR.
848 .PP
849 To parse this code, Perl uses a heuristic based on what package names
850 it has seen, what subroutines exist in the current package, what
851 barewords it has previously seen, and other input. Needless to say,
852 heuristics can produce very surprising results!
853 .PP
854 Older documentation (and some CPAN modules) encouraged this syntax,
855 particularly for constructors, so you may still find it in the wild.
856 However, we encourage you to avoid using it in new code.
857 .PP
858 You can force Perl to interpret the bareword as a class name by
859 appending \f(CW\*(C`::\*(C'\fR to it, like we saw earlier:
860 .PP
861 .Vb 1
862 \& my $file = new File:: $path, $data;
863 .Ve
864 .PP
865 Indirect object syntax is only available when the
866 \&\f(CW"indirect"\fR named feature is enabled.
867 This is enabled by default, but can be disabled if requested. This
868 feature is present in older feature version bundles, but was removed
869 from the \f(CW\*(C`:5.36\*(C'\fR bundle; so a \f(CW\*(C`use VERSION\*(C'\fR
870 declaration of \f(CW\*(C`v5.36\*(C'\fR or above will also disable the feature.
871 .PP
872 .Vb 2
873 \& use v5.36;
874 \& # indirect object syntax is no longer available
875 .Ve
876 .ie n .SS """bless"", ""blessed"", and ""ref"""
877 .el .SS "\f(CWbless\fP, \f(CWblessed\fP, and \f(CWref\fP"
878 .IX Subsection "bless, blessed, and ref"
879 As we saw earlier, an object is simply a data structure that has been
880 blessed into a class via the \f(CW\*(C`bless\*(C'\fR function. The \f(CW\*(C`bless\*(C'\fR function
881 can take either one or two arguments:
882 .PP
883 .Vb 2
884 \& my $object = bless {}, $class;
885 \& my $object = bless {};
886 .Ve
887 .PP
888 In the first form, the anonymous hash is being blessed into the class
889 in \f(CW$class\fR. In the second form, the anonymous hash is blessed into
890 the current package.
891 .PP
892 The second form is strongly discouraged, because it breaks the ability
893 of a subclass to reuse the parent\*(Aqs constructor, but you may still run
894 across it in existing code.
895 .PP
896 If you want to know whether a particular scalar refers to an object,
897 you can use the \f(CW\*(C`blessed\*(C'\fR function exported by Scalar::Util, which
898 is shipped with the Perl core.
899 .PP
900 .Vb 1
901 \& use Scalar::Util \*(Aqblessed\*(Aq;
902 \&
903 \& if ( defined blessed($thing) ) { ... }
904 .Ve
905 .PP
906 If \f(CW$thing\fR refers to an object, then this function returns the name
907 of the package the object has been blessed into. If \f(CW$thing\fR doesn\*(Aqt
908 contain a reference to a blessed object, the \f(CW\*(C`blessed\*(C'\fR function
909 returns \f(CW\*(C`undef\*(C'\fR.
910 .PP
911 Note that \f(CWblessed($thing)\fR will also return false if \f(CW$thing\fR has
912 been blessed into a class named "0". This is possible, but quite
913 pathological. Don\*(Aqt create a class named "0" unless you know what
914 you\*(Aqre doing.
915 .PP
916 Similarly, Perl\*(Aqs built\-in \f(CW\*(C`ref\*(C'\fR function treats a reference to a
917 blessed object specially. If you call \f(CWref($thing)\fR and \f(CW$thing\fR
918 holds a reference to an object, it will return the name of the class
919 that the object has been blessed into.
920 .PP
921 If you simply want to check that a variable contains an object
922 reference, we recommend that you use \f(CW\*(C`defined blessed($object)\*(C'\fR, since
923 \&\f(CW\*(C`ref\*(C'\fR returns true values for all references, not just objects.
924 .SS "The UNIVERSAL Class"
925 .IX Xref "UNIVERSAL"
926 .IX Subsection "The UNIVERSAL Class"
927 All classes automatically inherit from the UNIVERSAL class, which is
928 built\-in to the Perl core. This class provides a number of methods, all
929 of which can be called on either a class or an object. You can also
930 choose to override some of these methods in your class. If you do so,
931 we recommend that you follow the built\-in semantics described below.
932 .IP isa($class) 4
933 .IX Xref "isa"
934 .IX Item "isa($class)"
935 The \f(CW\*(C`isa\*(C'\fR method returns \fItrue\fR if the object is a member of the
936 class in \f(CW$class\fR, or a member of a subclass of \f(CW$class\fR.
937 .Sp
938 If you override this method, it should never throw an exception.
939 .IP DOES($role) 4
940 .IX Xref "DOES"
941 .IX Item "DOES($role)"
942 The \f(CW\*(C`DOES\*(C'\fR method returns \fItrue\fR if its object claims to perform the
943 role \f(CW$role\fR. By default, this is equivalent to \f(CW\*(C`isa\*(C'\fR. This method is
944 provided for use by object system extensions that implement roles, like
945 \&\f(CW\*(C`Moose\*(C'\fR and \f(CW\*(C`Role::Tiny\*(C'\fR.
946 .Sp
947 You can also override \f(CW\*(C`DOES\*(C'\fR directly in your own classes. If you
948 override this method, it should never throw an exception.
949 .IP can($method) 4
950 .IX Xref "can"
951 .IX Item "can($method)"
952 The \f(CW\*(C`can\*(C'\fR method checks to see if the class or object it was called on
953 has a method named \f(CW$method\fR. This checks for the method in the class
954 and all of its parents. If the method exists, then a reference to the
955 subroutine is returned. If it does not then \f(CW\*(C`undef\*(C'\fR is returned.
956 .Sp
957 If your class responds to method calls via \f(CW\*(C`AUTOLOAD\*(C'\fR, you may want to
958 overload \f(CW\*(C`can\*(C'\fR to return a subroutine reference for methods which your
959 \&\f(CW\*(C`AUTOLOAD\*(C'\fR method handles.
960 .Sp
961 If you override this method, it should never throw an exception.
962 .IP VERSION($need) 4
963 .IX Xref "VERSION"
964 .IX Item "VERSION($need)"
965 The \f(CW\*(C`VERSION\*(C'\fR method returns the version number of the class
966 (package).
967 .Sp
968 If the \f(CW$need\fR argument is given then it will check that the current
969 version (as defined by the \f(CW$VERSION\fR variable in the package) is greater
970 than or equal to \f(CW$need\fR; it will die if this is not the case. This
971 method is called automatically by the \f(CW\*(C`VERSION\*(C'\fR form of \f(CW\*(C`use\*(C'\fR.
972 .Sp
973 .Vb 3
974 \& use Package 1.2 qw(some imported subs);
975 \& # implies:
976 \& Package\->VERSION(1.2);
977 .Ve
978 .Sp
979 We recommend that you use this method to access another package\*(Aqs
980 version, rather than looking directly at \f(CW$Package::VERSION\fR. The
981 package you are looking at could have overridden the \f(CW\*(C`VERSION\*(C'\fR method.
982 .Sp
983 We also recommend using this method to check whether a module has a
984 sufficient version. The internal implementation uses the version
985 module to make sure that different types of version numbers are
986 compared correctly.
987 .SS AUTOLOAD
988 .IX Xref "AUTOLOAD"
989 .IX Subsection "AUTOLOAD"
990 If you call a method that doesn\*(Aqt exist in a class, Perl will throw an
991 error. However, if that class or any of its parent classes defines an
992 \&\f(CW\*(C`AUTOLOAD\*(C'\fR method, that \f(CW\*(C`AUTOLOAD\*(C'\fR method is called instead.
993 .PP
994 \&\f(CW\*(C`AUTOLOAD\*(C'\fR is called as a regular method, and the caller will not know
995 the difference. Whatever value your \f(CW\*(C`AUTOLOAD\*(C'\fR method returns is
996 returned to the caller.
997 .PP
998 The fully qualified method name that was called is available in the
999 \&\f(CW$AUTOLOAD\fR package global for your class. Since this is a global, if
1000 you want to refer to it without a package name prefix under \f(CWstrict
1001 \&\*(Aqvars\*(Aq\fR, you need to declare it.
1002 .PP
1003 .Vb 5
1004 \& # XXX \- this is a terrible way to implement accessors, but it makes
1005 \& # for a simple example.
1006 \& our $AUTOLOAD;
1007 \& sub AUTOLOAD {
1008 \& my $self = shift;
1009 \&
1010 \& # Remove qualifier from original method name...
1011 \& my $called = $AUTOLOAD =~ s/.*:://r;
1012 \&
1013 \& # Is there an attribute of that name?
1014 \& die "No such attribute: $called"
1015 \& unless exists $self\->{$called};
1016 \&
1017 \& # If so, return it...
1018 \& return $self\->{$called};
1019 \& }
1020 \&
1021 \& sub DESTROY { } # see below
1022 .Ve
1023 .PP
1024 Without the \f(CW\*(C`our $AUTOLOAD\*(C'\fR declaration, this code will not compile
1025 under the strict pragma.
1026 .PP
1027 As the comment says, this is not a good way to implement accessors.
1028 It\*(Aqs slow and too clever by far. However, you may see this as a way to
1029 provide accessors in older Perl code. See perlootut for
1030 recommendations on OO coding in Perl.
1031 .PP
1032 If your class does have an \f(CW\*(C`AUTOLOAD\*(C'\fR method, we strongly recommend
1033 that you override \f(CW\*(C`can\*(C'\fR in your class as well. Your overridden \f(CW\*(C`can\*(C'\fR
1034 method should return a subroutine reference for any method that your
1035 \&\f(CW\*(C`AUTOLOAD\*(C'\fR responds to.
1036 .SS Destructors
1037 .IX Xref "destructor DESTROY"
1038 .IX Subsection "Destructors"
1039 When the last reference to an object goes away, the object is
1040 destroyed. If you only have one reference to an object stored in a
1041 lexical scalar, the object is destroyed when that scalar goes out of
1042 scope. If you store the object in a package global, that object may not
1043 go out of scope until the program exits.
1044 .PP
1045 If you want to do something when the object is destroyed, you can
1046 define a \f(CW\*(C`DESTROY\*(C'\fR method in your class. This method will always be
1047 called by Perl at the appropriate time, unless the method is empty.
1048 .PP
1049 This is called just like any other method, with the object as the first
1050 argument. It does not receive any additional arguments. However, the
1051 \&\f(CW$_[0]\fR variable will be read\-only in the destructor, so you cannot
1052 assign a value to it.
1053 .PP
1054 If your \f(CW\*(C`DESTROY\*(C'\fR method throws an exception, this will not cause
1055 any control transfer beyond exiting the method. The exception will be
1056 reported to \f(CW\*(C`STDERR\*(C'\fR as a warning, marked "(in cleanup)", and Perl will
1057 continue with whatever it was doing before.
1058 .PP
1059 Because \f(CW\*(C`DESTROY\*(C'\fR methods can be called at any time, you should localize
1060 any global status variables that might be set by anything you do in
1061 your \f(CW\*(C`DESTROY\*(C'\fR method. If you are in doubt about a particular status
1062 variable, it doesn\*(Aqt hurt to localize it. There are five global status
1063 variables, and the safest way is to localize all five of them:
1064 .PP
1065 .Vb 5
1066 \& sub DESTROY {
1067 \& local($., $@, $!, $^E, $?);
1068 \& my $self = shift;
1069 \& ...;
1070 \& }
1071 .Ve
1072 .PP
1073 If you define an \f(CW\*(C`AUTOLOAD\*(C'\fR in your class, then Perl will call your
1074 \&\f(CW\*(C`AUTOLOAD\*(C'\fR to handle the \f(CW\*(C`DESTROY\*(C'\fR method. You can prevent this by
1075 defining an empty \f(CW\*(C`DESTROY\*(C'\fR, like we did in the autoloading example.
1076 You can also check the value of \f(CW$AUTOLOAD\fR and return without doing
1077 anything when called to handle \f(CW\*(C`DESTROY\*(C'\fR.
1078 .PP
1079 \fIGlobal Destruction\fR
1080 .IX Subsection "Global Destruction"
1081 .PP
1082 The order in which objects are destroyed during the global destruction
1083 before the program exits is unpredictable. This means that any objects
1084 contained by your object may already have been destroyed. You should
1085 check that a contained object is defined before calling a method on it:
1086 .PP
1087 .Vb 2
1088 \& sub DESTROY {
1089 \& my $self = shift;
1090 \&
1091 \& $self\->{handle}\->close() if $self\->{handle};
1092 \& }
1093 .Ve
1094 .PP
1095 You can use the \f(CW\*(C`${^GLOBAL_PHASE}\*(C'\fR variable to detect if you are
1096 currently in the global destruction phase:
1097 .PP
1098 .Vb 2
1099 \& sub DESTROY {
1100 \& my $self = shift;
1101 \&
1102 \& return if ${^GLOBAL_PHASE} eq \*(AqDESTRUCT\*(Aq;
1103 \&
1104 \& $self\->{handle}\->close();
1105 \& }
1106 .Ve
1107 .PP
1108 Note that this variable was added in Perl 5.14.0. If you want to detect
1109 the global destruction phase on older versions of Perl, you can use the
1110 \&\f(CW\*(C`Devel::GlobalDestruction\*(C'\fR module on CPAN.
1111 .PP
1112 If your \f(CW\*(C`DESTROY\*(C'\fR method issues a warning during global destruction,
1113 the Perl interpreter will append the string " during global
1114 destruction" to the warning.
1115 .PP
1116 During global destruction, Perl will always garbage collect objects
1117 before unblessed references. See "PERL_DESTRUCT_LEVEL" in perlhacktips
1118 for more information about global destruction.
1119 .SS "Non\-Hash Objects"
1120 .IX Subsection "Non-Hash Objects"
1121 All the examples so far have shown objects based on a blessed hash.
1122 However, it\*(Aqs possible to bless any type of data structure or referent,
1123 including scalars, globs, and subroutines. You may see this sort of
1124 thing when looking at code in the wild.
1125 .PP
1126 Here\*(Aqs an example of a module as a blessed scalar:
1127 .PP
1128 .Vb 1
1129 \& package Time;
1130 \&
1131 \& use v5.36;
1132 \&
1133 \& sub new {
1134 \& my $class = shift;
1135 \&
1136 \& my $time = time;
1137 \& return bless \e$time, $class;
1138 \& }
1139 \&
1140 \& sub epoch {
1141 \& my $self = shift;
1142 \& return $$self;
1143 \& }
1144 \&
1145 \& my $time = Time\->new();
1146 \& print $time\->epoch();
1147 .Ve
1148 .SS "Inside\-Out objects"
1149 .IX Subsection "Inside-Out objects"
1150 In the past, the Perl community experimented with a technique called
1151 "inside\-out objects". An inside\-out object stores its data outside of
1152 the object\*(Aqs reference, indexed on a unique property of the object,
1153 such as its memory address, rather than in the object itself. This has
1154 the advantage of enforcing the encapsulation of object attributes,
1155 since their data is not stored in the object itself.
1156 .PP
1157 This technique was popular for a while (and was recommended in Damian
1158 Conway\*(Aqs \fIPerl Best Practices\fR), but never achieved universal
1159 adoption. The Object::InsideOut module on CPAN provides a
1160 comprehensive implementation of this technique, and you may see it or
1161 other inside\-out modules in the wild.
1162 .PP
1163 Here is a simple example of the technique, using the
1164 Hash::Util::FieldHash core module. This module was added to the core
1165 to support inside\-out object implementations.
1166 .PP
1167 .Vb 1
1168 \& package Time;
1169 \&
1170 \& use v5.36;
1171 \&
1172 \& use Hash::Util::FieldHash \*(Aqfieldhash\*(Aq;
1173 \&
1174 \& fieldhash my %time_for;
1175 \&
1176 \& sub new {
1177 \& my $class = shift;
1178 \&
1179 \& my $self = bless \e( my $object ), $class;
1180 \&
1181 \& $time_for{$self} = time;
1182 \&
1183 \& return $self;
1184 \& }
1185 \&
1186 \& sub epoch {
1187 \& my $self = shift;
1188 \&
1189 \& return $time_for{$self};
1190 \& }
1191 \&
1192 \& my $time = Time\->new;
1193 \& print $time\->epoch;
1194 .Ve
1195 .SS Pseudo\-hashes
1196 .IX Subsection "Pseudo-hashes"
1197 The pseudo\-hash feature was an experimental feature introduced in
1198 earlier versions of Perl and removed in 5.10.0. A pseudo\-hash is an
1199 array reference which can be accessed using named keys like a hash. You
1200 may run into some code in the wild which uses it. See the fields
1201 pragma for more information.
1202 .SH "SEE ALSO"
1203 .IX Header "SEE ALSO"
1204 A kinder, gentler tutorial on object\-oriented programming in Perl can
1205 be found in perlootut. You should also check out perlmodlib for
1206 some style guides on constructing both modules and classes.