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