perlclass - Perl class syntax reference
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;
This document describes the syntax of the Perl's class feature, which provides native keywords supporting object-oriented programming paradigm.
class
Since Perl 5, support for objects revolved around the concept of blessing references with a package name. Such 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.
Class feature is a core implementation of class syntax which is familiar to what one would find in other programming languages. It isn't a bless wrapper, but a completely new system built right into the perl interpreter.
bless
Enabling the class feature allows the usage of the following new keywords in the scope of current package:
class NAME BLOCK class NAME VERSION BLOCK class NAME; class NAME VERSION;
The class keyword declares a new package which is intended to be a class. All other keywords from the class feature should be used in 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 file is used up until the next class or package statement.
package
class and package declarations are similar, but classes automatically get a constructor named new - You don't have to (and should not) write one. Additionally, in the class BLOCK you are allowed to declare fields and methods.
new
field VARIABLE_NAME; field VARIABLE_NAME = EXPR; field VARIABLE_NAME : ATTRIBUTES; field VARIABLE_NAME : ATTRIBUTES = EXPR;
Fields are variables which are visible in the scope of the class - more specifically within "method" and ADJUST blocks. Each class instance get their own storage of fields, independent of each other.
ADJUST
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 see any other variables in scope.
class WithACounter { my $next_count = 1; field $count = $next_count++; }
When combined with the :param field attribute, the defaulting expression can use any of the =, //= or ||= operators. Expressions using = will apply whenever the caller did not pass the corresponding parameter to the constructor at all. Expressions using //= will also apply if the caller did pass the parameter but the value was undefined, and expressions using ||= will apply if the value was false.
:param
=
//=
||=
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 $self populated with the current object instance will automatically be created in the lexical scope of method.
$self
method
Methods always act as if use feature 'signatures' is in effect, but $self will not appear in the arguments list as far as the signature is concerned.
use feature 'signatures'
class WithMethods { field $greetings; ADJUST { $greetings = "Hello"; } method greet($name = "someone") { say "$greetings, $name"; } }
Just like regular subroutines, methods can be anonymous:
class AnonMethodFactory { method get_anon_method { return method { return 'this is an anonymous method'; }; } }
Specific aspects of the keywords mentioned above are managed using 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.
Classes may inherit from one superclass, by using the :isa class attribute.
:isa
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 :isa attribute may request a minimum version of the base class; it is applied similar to use - if the provided version is too low it will fail at compile time.
use
class Example::Subclass :isa(Example::Base 2.345) { ... }
The :isa attribute will attempt to require the named module if it is not already loaded.
require
A scalar field with a :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 $ 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.
None yet.
Each object begins its life with a constructor call. The constructor is always named new and is invoked like a method call on the class name:
my $object = My::Class->new(%arguments);
During the construction, class fields are compared to %arguments hash and populated where possible.
%arguments
Object adjustment can be performed during the construction to run user-defined code. It is done with the help of ADJUST blocks, which are called in order of declaration.
They are similar to BEGIN blocks, which run during the compilation of a package. However, they also have access to $self lexical (object instance) and all object fields created up to that point.
BEGIN
After the construction phase, object is ready to be used.
Using blessed (Scalar::Util::blessed or builtin::blessed) on the object will return the name of the class, while reftype (Scalar::Util::reftype or builtin::reftype) will return the string 'OBJECT'.
blessed
Scalar::Util::blessed
builtin::blessed
reftype
Scalar::Util::reftype
builtin::reftype
'OBJECT'
Just like with other references, when object reference count reaches zero it will automatically be destroyed.
This feature is still experimental and very incomplete. The following list gives some overview of the kinds of work still to be added or changed:
Roles
Some syntax for declaring a role (likely a role keyword), and for consuming a role into a class (likely a :does() attribute).
role
:does()
Parameters to ADJUST blocks
Some syntax for declaring that an 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);
ADJUST blocks as true blocks
Currently, every ADJUST block is wrapped in its own CV 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.
Accessor generator attributes
Attributes to request that accessor methods be generated for fields. Likely :reader and :writer.
:reader
:writer
class X { field $name :reader; }
Equivalent to
class X { field $name; method name { return $name; } }
Metaprogramming
An extension of the metaprogramming API (currently proposed by RFC0022) which adds knowledge of classes, methods, fields, ADJUST blocks, and other such class-related details.
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.
Paul Evans
Bartosz Jarzyna
To install less, copy and paste the appropriate command in to your terminal.
cpanm
cpanm less
CPAN shell
perl -MCPAN -e shell install less
For more information on module installation, please visit the detailed CPAN module installation guide.