Debian Codegraph @

upstream/debian-unstable/man1/perlclass.1

raw
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 "PERLCLASS 1"
58 .TH PERLCLASS 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 perlclass \- Perl class syntax reference
65 .SH SYNOPSIS
66 .IX Header "SYNOPSIS"
67 .Vb 2
68 \& use v5.38;
69 \& use feature \*(Aqclass\*(Aq;
70 \&
71 \& class My::Example 1.234 {
72 \& field $x;
73 \&
74 \& ADJUST {
75 \& $x = "Hello, world";
76 \& }
77 \&
78 \& method print_message {
79 \& say $x;
80 \& }
81 \& }
82 \&
83 \& My::Example\->new\->print_message;
84 .Ve
85 .SH DESCRIPTION
86 .IX Header "DESCRIPTION"
87 This document describes the syntax of Perl's \f(CW\*(C`class\*(C'\fR feature, which provides
88 native keywords for object-oriented programming.
89 .SS History
90 .IX Subsection "History"
91 Since Perl 5, support for objects revolved around the concept of \fIblessing\fR
92 references with a package name (see "bless REF,CLASSNAME" in perlfunc). Such a
93 reference could then be used to call subroutines from the package it was
94 blessed with (or any of its parents). This system, while bare-bones, was
95 flexible enough to allow creation of multiple more advanced, community-driven
96 systems for object orientation. For more information, see perlmod and
97 perlobj.
98 .PP
99 The \f(CW\*(C`class\*(C'\fR feature is a core implementation of a class syntax that is similar
100 to what one would find in other programming languages. It is not a wrapper
101 around \f(CW\*(C`bless\*(C'\fR, but a completely new system built right into the perl
102 interpreter.
103 .SH KEYWORDS
104 .IX Header "KEYWORDS"
105 Enabling the \f(CW\*(C`class\*(C'\fR feature allows the usage of the following new keywords in
106 the current lexical scope:
107 .SS class
108 .IX Subsection "class"
109 .Vb 1
110 \& class NAME BLOCK
111 \&
112 \& class NAME VERSION BLOCK
113 \&
114 \& class NAME VERSION : ATTRIBUTES... BLOCK
115 \&
116 \& class NAME;
117 \&
118 \& class NAME VERSION;
119 \&
120 \& class NAME VERSION : ATTRIBUTES...;
121 .Ve
122 .PP
123 The \f(CW\*(C`class\*(C'\fR keyword declares a new package (see "Packages" in perlmod) that is
124 intended to be a class. All other keywords from the \f(CW\*(C`class\*(C'\fR feature should be
125 used within the scope of this declaration.
126 .PP
127 .Vb 3
128 \& class WithVersion 1.000 {
129 \& # class definition goes here
130 \& }
131 .Ve
132 .PP
133 Classes can be declared in either block or statement syntax. If a block is
134 used, the body of the block contains the implementation of the class. If the
135 statement form is used, the remainder of the file is used up until the next
136 \&\f(CW\*(C`class\*(C'\fR or \f(CW\*(C`package\*(C'\fR statement.
137 .PP
138 A \f(CW\*(C`class\*(C'\fR declaration can optionally have a version number, similar to the
139 \&\f(CW\*(C`package\*(C'\fR keyword. It can also optionally have attributes. If both are
140 specified, the version number must come first, before the attributes.
141 .PP
142 \&\f(CW\*(C`class\*(C'\fR and \f(CW\*(C`package\*(C'\fR declarations are similar, but classes automatically get
143 a constructor named \f(CW\*(C`new\*(C'\fR \- you don't have to (and should not) write one.
144 Additionally, in the class BLOCK you are allowed to declare fields and methods.
145 .SS field
146 .IX Subsection "field"
147 .Vb 1
148 \& field VARIABLE_NAME;
149 \&
150 \& field VARIABLE_NAME = EXPR;
151 \&
152 \& field VARIABLE_NAME : ATTRIBUTES;
153 \&
154 \& field VARIABLE_NAME : ATTRIBUTES = EXPR;
155 .Ve
156 .PP
157 Fields are variables that are visible in the scope of the class \- more
158 specifically within "method" and ADJUST blocks. Each class
159 instance gets its own storage of fields, independent of other instances.
160 .PP
161 A field behaves like a normal lexically scoped variable. It has a sigil and is
162 private to the class (though creation of an accessor method will make it
163 accessible from the outside). The main difference is that different instances
164 access different values in the same scope.
165 .PP
166 .Vb 5
167 \& class WithFields {
168 \& field $scalar = 42;
169 \& field @array = qw(this is just an array);
170 \& field %hash = (species => \*(AqMartian\*(Aq, planet => \*(AqMars\*(Aq);
171 \& }
172 .Ve
173 .PP
174 Fields may optionally have initializing expressions. If present, the expression
175 will be evaluated within the constructor of each object instance. During each
176 evaluation, the expression can use the value of any previously-set field, as
177 well as any other variables in scope.
178 .PP
179 .Vb 4
180 \& class WithACounter {
181 \& my $next_count = 1;
182 \& field $count = $next_count++;
183 \& }
184 .Ve
185 .PP
186 When combined with the \f(CW\*(C`:param\*(C'\fR field attribute, the defaulting expression can
187 use any of the \f(CW\*(C`=\*(C'\fR, \f(CW\*(C`//=\*(C'\fR or \f(CW\*(C`||=\*(C'\fR operators. Expressions using \f(CW\*(C`=\*(C'\fR will
188 apply whenever the caller did not pass the corresponding parameter to the
189 constructor at all. Expressions using \f(CW\*(C`//=\*(C'\fR will also apply if the caller did
190 pass the parameter but the value was undefined, and expressions using \f(CW\*(C`||=\*(C'\fR
191 will apply if the value was false.
192 .PP
193 During a field initializing expression, the instance is not yet constructed
194 and so the \f(CW$self\fR lexical is not available. However, the special
195 \&\f(CW\*(C`_\|_CLASS_\|_\*(C'\fR token may be used to obtain the name of the class being
196 constructed, for example in order to invoke class methods on it to help in
197 constructing values for fields.
198 .PP
199 .Vb 4
200 \& class WithCustomField {
201 \& use constant DEFAULT_X => 10;
202 \& field $x = _\|_CLASS_\|_\->DEFAULT_X;
203 \& }
204 .Ve
205 .PP
206 This allows subclasses to override the method with different behaviour.
207 .PP
208 .Vb 3
209 \& class DifferentCustomField :isa(WithCustomField) {
210 \& sub DEFAULT_X { rand > 0.5 ? 20 : 30 }
211 \& }
212 .Ve
213 .PP
214 When an instance of \f(CW\*(C`DifferentCustomField\*(C'\fR is constructed, the \f(CW\*(C`_\|_CLASS_\|_\*(C'\fR
215 expression in the base will yield the correct class name, and so invoke this
216 overridden method instead.
217 .SS method
218 .IX Subsection "method"
219 .Vb 1
220 \& method METHOD_NAME SIGNATURE BLOCK
221 \&
222 \& method METHOD_NAME BLOCK
223 \&
224 \& method SIGNATURE BLOCK
225 \&
226 \& method BLOCK
227 .Ve
228 .PP
229 Methods are subroutines intended to be called in the context of class objects.
230 .PP
231 A variable named \f(CW$self\fR populated with the current object instance will
232 automatically be created in the lexical scope of \f(CW\*(C`method\*(C'\fR.
233 .PP
234 Methods always act as if \f(CW\*(C`use feature \*(Aqsignatures\*(Aq\*(C'\fR is in effect, but \f(CW$self\fR
235 will not appear in the arguments list as far as the signature is concerned.
236 .PP
237 .Vb 2
238 \& class WithMethods {
239 \& field $greetings;
240 \&
241 \& ADJUST {
242 \& $greetings = "Hello";
243 \& }
244 \&
245 \& method greet($name = "someone") {
246 \& say "$greetings, $name";
247 \& }
248 \& }
249 .Ve
250 .PP
251 Just like regular subroutines, methods \fIcan\fR be anonymous:
252 .PP
253 .Vb 1
254 \& class AnonMethodFactory {
255 \&
256 \& method get_anon_method {
257 \& return method {
258 \& return \*(Aqthis is an anonymous method\*(Aq;
259 \& };
260 \& }
261 \& }
262 .Ve
263 .SH ATTRIBUTES
264 .IX Header "ATTRIBUTES"
265 Specific aspects of the keywords mentioned above are managed using
266 \&\fIattributes\fR. Attributes all start with a colon, and one or more of them can
267 be appended after the item's name, separated by a space.
268 .SS "Class attributes"
269 .IX Subsection "Class attributes"
270 \fI:isa\fR
271 .IX Subsection ":isa"
272 .PP
273 Classes may inherit from \fBone\fR superclass, by using the \f(CW\*(C`:isa\*(C'\fR class
274 attribute.
275 .PP
276 .Vb 1
277 \& class Example::Base { ... }
278 \&
279 \& class Example::Subclass :isa(Example::Base) { ... }
280 .Ve
281 .PP
282 Inherited methods are visible and may be invoked. Fields are always lexical
283 and therefore not visible by inheritance.
284 .PP
285 The \f(CW\*(C`:isa\*(C'\fR attribute may request a minimum version of the base class. As with
286 \&\f(CW\*(C`use MODULE VERSION\*(C'\fR, if the actual version of the base class is too low,
287 compilation will fail.
288 .PP
289 .Vb 1
290 \& class Example::Subclass :isa(Example::Base 2.345) { ... }
291 .Ve
292 .PP
293 The \f(CW\*(C`:isa\*(C'\fR attribute will attempt to \f(CW\*(C`require\*(C'\fR the named module if it is not
294 already loaded.
295 .SS "Field attributes"
296 .IX Subsection "Field attributes"
297 \fI:param\fR
298 .IX Subsection ":param"
299 .PP
300 A scalar field with a \f(CW\*(C`:param\*(C'\fR attribute will take its value from a named
301 parameter passed to the constructor. By default the parameter will have the
302 same name as the field (minus its leading \f(CW\*(C`$\*(C'\fR sigil), but a different name
303 can be specified in the attribute.
304 .PP
305 .Vb 2
306 \& field $x :param;
307 \& field $y :param(the_y_value);
308 .Ve
309 .PP
310 If there is no defaulting expression, then the parameter is required by the
311 constructor; the caller must pass it or an exception is thrown. With a
312 defaulting expression this becomes optional.
313 .PP
314 \fI:reader\fR
315 .IX Subsection ":reader"
316 .PP
317 A field with a \f(CW\*(C`:reader\*(C'\fR attribute will generate a reader accessor method
318 automatically. The generated method will have an empty (i.e. zero-argument)
319 signature, and its body will simply return the value of the field variable.
320 .PP
321 .Vb 1
322 \& field $s :reader;
323 \&
324 \& # Equivalent to
325 \& field $s;
326 \& method s () { return $s; }
327 .Ve
328 .PP
329 By default the accessor method will have the same name as the field (minus the
330 leading sigil), but a different name can be specified in the attribute's value.
331 .PP
332 .Vb 1
333 \& field $x :reader(get_x);
334 \&
335 \& # Generates a method
336 \& method get_x () { return $x; }
337 .Ve
338 .PP
339 Reader methods can be applied to non-scalar fields. When invoked in list
340 context, they yield the contents of the field; in scalar context they yield
341 the count of elements, as if the field variable had been placed in scalar
342 context.
343 .PP
344 .Vb 2
345 \& field @users :reader;
346 \& ...
347 \&
348 \& scalar $instance\->users;
349 .Ve
350 .SS "Method attributes"
351 .IX Subsection "Method attributes"
352 None yet.
353 .SH "OBJECT LIFECYCLE"
354 .IX Header "OBJECT LIFECYCLE"
355 .SS Construction
356 .IX Subsection "Construction"
357 Each object begins its life with a constructor call. The constructor is always
358 named \f(CW\*(C`new\*(C'\fR and is invoked like a method call on the class name:
359 .PP
360 .Vb 1
361 \& my $object = My::Class\->new(%arguments);
362 .Ve
363 .PP
364 During object construction, class fields are looked up in the \f(CW%arguments\fR
365 hash and populated where possible.
366 .SS Adjustment
367 .IX Subsection "Adjustment"
368 Object adjustment is a way to run arbitrary user-defined code during object
369 construction. This is done by placing code in \f(CW\*(C`ADJUST\*(C'\fR blocks. Every time an
370 object is constructed, its \f(CW\*(C`ADJUST\*(C'\fR blocks are executed (in the order in which
371 they are declared).
372 .PP
373 .Vb 9
374 \& class WellAdjusted {
375 \& field $x :param;
376 \& ADJUST {
377 \& say "Hello!";
378 \& }
379 \& ADJUST {
380 \& say "x = $x";
381 \& }
382 \& }
383 \&
384 \& my $object = WellAdjusted\->new(x => 42);
385 \& # Output:
386 \& # Hello!
387 \& # x = 42
388 .Ve
389 .PP
390 \&\f(CW\*(C`ADJUST\*(C'\fR blocks are syntactically similar to \f(CW\*(C`BEGIN\*(C'\fR or \f(CW\*(C`INIT\*(C'\fR
391 blocks, which only run once.
392 However, \f(CW\*(C`ADJUST\*(C'\fR blocks, like methods, have access to \f(CW$self\fR (a lexical
393 variable holding the object being constructed) as well as all object fields
394 created up to that point.
395 .SS Lifetime
396 .IX Subsection "Lifetime"
397 After the construction phase, the object is ready to be used.
398 .PP
399 Using \f(CW\*(C`blessed\*(C'\fR (\f(CW\*(C`Scalar::Util::blessed\*(C'\fR or \f(CW\*(C`builtin::blessed\*(C'\fR) on the
400 object will return the name of the class, while \f(CW\*(C`reftype\*(C'\fR
401 (\f(CW\*(C`Scalar::Util::reftype\*(C'\fR or \f(CW\*(C`builtin::reftype\*(C'\fR) will return the string
402 \&\f(CW\*(AqOBJECT\*(Aq\fR.
403 .SS Destruction
404 .IX Subsection "Destruction"
405 An object is destroyed when the last reference to it goes away, just as with
406 other data structures in Perl.
407 .SH TODO
408 .IX Header "TODO"
409 This feature is still experimental and very incomplete. The following list
410 gives an overview of features still to be added or changed:
411 .IP \(bu 4
412 Roles
413 .Sp
414 Some syntax for declaring a role (likely a \f(CW\*(C`role\*(C'\fR keyword), and for consuming
415 a role into a class (likely a \f(CW:does()\fR attribute).
416 .IP \(bu 4
417 Parameters to ADJUST blocks
418 .Sp
419 Some syntax for declaring that an \f(CW\*(C`ADJUST\*(C'\fR block can consume named
420 parameters, which become part of the class constructor's API. This might be
421 inspired by a similar plan to add named arguments to subroutine signatures.
422 .Sp
423 .Vb 5
424 \& class X {
425 \& ADJUST (:$alpha, :$beta = 123) {
426 \& ...
427 \& }
428 \& }
429 \&
430 \& my $obj = X\->new(alpha => 456);
431 .Ve
432 .IP \(bu 4
433 ADJUST blocks as true blocks
434 .Sp
435 Currently, every ADJUST block is wrapped in its own CV (subroutine) that gets
436 invoked with the full ENTERSUB overhead. It should be possible to use the same
437 mechanism that makes all field initializer expressions appear within the same
438 CV on ADJUST blocks as well, merging them all into a single CV per class. This
439 will make it faster to invoke if a class has more than one of them.
440 .IP \(bu 4
441 More accessor generator attributes
442 .Sp
443 Attributes to request that other kinds of accessor methods be generated for
444 fields. Likely \f(CW\*(C`:writer\*(C'\fR.
445 .Sp
446 .Vb 3
447 \& class X {
448 \& field $name :writer;
449 \& }
450 .Ve
451 .Sp
452 Equivalent to
453 .Sp
454 .Vb 4
455 \& class X {
456 \& field $name;
457 \& method set_name ($new) { $name = $new; return $self; }
458 \& }
459 .Ve
460 .IP \(bu 4
461 Metaprogramming
462 .Sp
463 An extension of the metaprogramming API (currently proposed by
464 PPC0022 <https://github.com/Perl/PPCs/pull/25>) which adds knowledge of
465 classes, methods, fields, ADJUST blocks, and other such class-related details.
466 .IP \(bu 4
467 Extension Customisation
468 .Sp
469 Ways in which out-of-core modules can interact with the class system,
470 including an ability for them to provide new class or field attributes.
471 .SH "KNOWN BUGS"
472 .IX Header "KNOWN BUGS"
473 The following bugs have been found in the experimental \f(CW\*(C`class\*(C'\fR feature:
474 .IP \(bu 4
475 Since Perl v5.38, inheriting from a parent class which is declared in the same
476 file and which hadn't already been sealed can cause a segmentation fault.
477 [GH #20890 <https://github.com/Perl/perl5/issues/20890>]
478 .IP \(bu 4
479 Since Perl v5.38 and with the experimental \f(CW\*(C`refaliasing\*(C'\fR feature, trying to
480 replace a field variable causes a segmentation fault.
481 [GH #20947 <https://github.com/Perl/perl5/issues/20947>]
482 .IP \(bu 4
483 Since Perl v5.38, it's possible to craft a class with leaky encapsulation,
484 which can cause a segmentation fault.
485 [GH #20956 <https://github.com/Perl/perl5/issues/20956>]
486 .IP \(bu 4
487 In Perl v5.38, inheriting from a class would not always attempt to load the
488 parent class (fixed in Perl v5.40).
489 [GH #21332 <https://github.com/Perl/perl5/issues/21332>]
490 .SH AUTHORS
491 .IX Header "AUTHORS"
492 Paul Evans
493 .PP
494 Bartosz Jarzyna