1PERLCLASS(1) Perl Programmers Reference Guide PERLCLASS(1)
2
3
4
6 perlclass - Perl class syntax reference
7
9 use v5.38;
10 use feature 'class';
11
12 class My::Example 1.234 {
13 field $x;
14
15 ADJUST {
16 $x = "Hello, world";
17 }
18
19 method print_message {
20 say $x;
21 }
22 }
23
24 My::Example->new->print_message;
25
27 This document describes the syntax of the Perl's "class" feature, which
28 provides native keywords supporting object-oriented programming
29 paradigm.
30
31 History
32 Since Perl 5, support for objects revolved around the concept of
33 blessing references with a package name. Such reference could then be
34 used to call subroutines from the package it was blessed with (or any
35 of its parents). This system, while bare-bones, was flexible enough to
36 allow creation of multiple more advanced, community-driven systems for
37 object orientation.
38
39 Class feature is a core implementation of class syntax which is
40 familiar to what one would find in other programming languages. It
41 isn't a "bless" wrapper, but a completely new system built right into
42 the perl interpreter.
43
45 Enabling the "class" feature allows the usage of the following new
46 keywords in the scope of current package:
47
48 class
49 class NAME BLOCK
50
51 class NAME VERSION BLOCK
52
53 class NAME;
54
55 class NAME VERSION;
56
57 The "class" keyword declares a new package which is intended to be a
58 class. All other keywords from the "class" feature should be used in
59 scope of this declaration.
60
61 class WithVersion 1.000 {
62 # class definition goes here
63 }
64
65 Classes can be declared in either block or statement syntax. If a block
66 is used, the body of the block contains the implementation of the
67 class. If the statement form is used, the remainder of the file is used
68 up until the next "class" or "package" statement.
69
70 "class" and "package" declarations are similar, but classes
71 automatically get a constructor named "new" - You don't have to (and
72 should not) write one. Additionally, in the class BLOCK you are
73 allowed to declare fields and methods.
74
75 field
76 field VARIABLE_NAME;
77
78 field VARIABLE_NAME = EXPR;
79
80 field VARIABLE_NAME : ATTRIBUTES;
81
82 field VARIABLE_NAME : ATTRIBUTES = EXPR;
83
84 Fields are variables which are visible in the scope of the class - more
85 specifically within "method" and "ADJUST" blocks. Each class instance
86 get their own storage of fields, independent of each other.
87
88 A field behaves like a normal lexically scoped variable. It has a sigil
89 and is private to the class (though creation of an accessor method will
90 make it accessible from the outside). The main difference is that
91 different instances access different values in the same scope.
92
93 class WithFields {
94 field $scalar = 42;
95 field @array = qw(this is just an array);
96 field %hash = (species => 'Martian', planet => 'Mars');
97 }
98
99 Fields may optionally have initializing expressions. If present, the
100 expression will be evaluated within the constructor of each object
101 instance. During each evaluation, the expression can use the value of
102 any previously-set field, as well as see any other variables in scope.
103
104 class WithACounter {
105 my $next_count = 1;
106 field $count = $next_count++;
107 }
108
109 When combined with the ":param" field attribute, the defaulting
110 expression can use any of the "=", "//=" or "||=" operators.
111 Expressions using "=" will apply whenever the caller did not pass the
112 corresponding parameter to the constructor at all. Expressions using
113 "//=" will also apply if the caller did pass the parameter but the
114 value was undefined, and expressions using "||=" will apply if the
115 value was false.
116
117 method
118 method METHOD_NAME SIGNATURE BLOCK
119
120 method METHOD_NAME BLOCK
121
122 method SIGNATURE BLOCK
123
124 method BLOCK
125
126 Methods are subroutines intended to be called in the context of class
127 objects.
128
129 A variable named $self populated with the current object instance will
130 automatically be created in the lexical scope of "method".
131
132 Methods always act as if "use feature 'signatures'" is in effect, but
133 $self will not appear in the arguments list as far as the signature is
134 concerned.
135
136 class WithMethods {
137 field $greetings;
138
139 ADJUST {
140 $greetings = "Hello";
141 }
142
143 method greet($name = "someone") {
144 say "$greetings, $name";
145 }
146 }
147
148 Just like regular subroutines, methods can be anonymous:
149
150 class AnonMethodFactory {
151
152 method get_anon_method {
153 return method {
154 return 'this is an anonymous method';
155 };
156 }
157 }
158
160 Specific aspects of the keywords mentioned above are managed using
161 attributes. Attributes all start with a colon, and one or more of them
162 can be appended after the item's name, separated by a space.
163
164 Class attributes
165 :isa
166
167 Classes may inherit from one superclass, by using the ":isa" class
168 attribute.
169
170 class Example::Base { ... }
171
172 class Example::Subclass :isa(Example::Base) { ... }
173
174 Inherited methods are visible and may be invoked. Fields are always
175 lexical and therefore not visible by inheritance.
176
177 The ":isa" attribute may request a minimum version of the base class;
178 it is applied similar to "use" - if the provided version is too low it
179 will fail at compile time.
180
181 class Example::Subclass :isa(Example::Base 2.345) { ... }
182
183 The ":isa" attribute will attempt to "require" the named module if it
184 is not already loaded.
185
186 Field attributes
187 :param
188
189 A scalar field with a ":param" attribute will take its value from a
190 named parameter passed to the constructor. By default the parameter
191 will have the same name as the field (minus its leading "$" sigil), but
192 a different name can be specified in the attribute.
193
194 field $x :param;
195 field $y :param(the_y_value);
196
197 If there is no defaulting expression then the parameter is required by
198 the constructor; the caller must pass it or an exception is thrown.
199 With a defaulting expression this becomes optional.
200
201 Method attributes
202 None yet.
203
205 Construction
206 Each object begins its life with a constructor call. The constructor is
207 always named "new" and is invoked like a method call on the class name:
208
209 my $object = My::Class->new(%arguments);
210
211 During the construction, class fields are compared to %arguments hash
212 and populated where possible.
213
214 Adjustment
215 Object adjustment can be performed during the construction to run user-
216 defined code. It is done with the help of "ADJUST" blocks, which are
217 called in order of declaration.
218
219 They are similar to "BEGIN" blocks, which run during the compilation of
220 a package. However, they also have access to $self lexical (object
221 instance) and all object fields created up to that point.
222
223 Lifetime
224 After the construction phase, object is ready to be used.
225
226 Using "blessed" ("Scalar::Util::blessed" or "builtin::blessed") on the
227 object will return the name of the class, while "reftype"
228 ("Scalar::Util::reftype" or "builtin::reftype") will return the string
229 'OBJECT'.
230
231 Destruction
232 Just like with other references, when object reference count reaches
233 zero it will automatically be destroyed.
234
236 This feature is still experimental and very incomplete. The following
237 list gives some overview of the kinds of work still to be added or
238 changed:
239
240 • Roles
241
242 Some syntax for declaring a role (likely a "role" keyword), and for
243 consuming a role into a class (likely a :does() attribute).
244
245 • Parameters to ADJUST blocks
246
247 Some syntax for declaring that an "ADJUST" block can consume named
248 parameters, which become part of the class constructor's API. This
249 might be inspired by a similar plan to add named arguments to
250 subroutine signatures.
251
252 class X {
253 ADJUST (:$alpha, :$beta = 123) {
254 ...
255 }
256 }
257
258 my $obj = X->new(alpha => 456);
259
260 • ADJUST blocks as true blocks
261
262 Currently, every ADJUST block is wrapped in its own CV that gets
263 invoked with the full ENTERSUB overhead. It should be possible to
264 use the same mechanism that makes all field initializer expressions
265 appear within the same CV on ADJUST blocks as well, merging them
266 all into a single CV per class. This will make it faster to invoke
267 if a class has more than one of them.
268
269 • Accessor generator attributes
270
271 Attributes to request that accessor methods be generated for
272 fields. Likely ":reader" and ":writer".
273
274 class X {
275 field $name :reader;
276 }
277
278 Equivalent to
279
280 class X {
281 field $name;
282 method name { return $name; }
283 }
284
285 • Metaprogramming
286
287 An extension of the metaprogramming API (currently proposed by
288 RFC0022 <https://github.com/Perl/RFCs/pull/25>) which adds
289 knowledge of classes, methods, fields, ADJUST blocks, and other
290 such class-related details.
291
292 • Extension Customisation
293
294 Ways in which out-of-core modules can interact with the class
295 system, including an ability for them to provide new class or field
296 attributes.
297
299 Paul Evans
300
301 Bartosz Jarzyna
302
303
304
305perl v5.38.2 2023-11-30 PERLCLASS(1)