Debian Codegraph @

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