PERLCLASS(1)

✨ NAME ✨

perlclass β€” the Perl class syntax reference, and honestly? It's giving main character energy. πŸ’…


🌸 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;

πŸ’– DESCRIPTION πŸ’–

Okay so this whole doc is about the syntax of Perl's class feature. It gives you native keywords for object-oriented programming. πŸ¦‹

πŸ•°οΈ History πŸ•°οΈ

Since Perl 5, support for objects was all about blessing references with a package name (peep "bless REF,CLASSNAME" in perlfunc). That reference could then call subroutines from the package it was blessed with (or any of its parents). This system was bare-bones but flexible enough to let the community build multiple more advanced object orientation systems. For more info, see perlmod and perlobj. πŸ’œ

The class feature is a core implementation of a class syntax that's similar to what you'd find in other programming languages. It is not a wrapper around bless β€” it's a completely new system built right into the perl interpreter. Periodt. πŸ”₯


πŸ”‘ KEYWORDS πŸ”‘

Enabling the class feature lets you use these new keywords in the current lexical scope:

🏷️ class

           class NAME BLOCK

           class NAME VERSION BLOCK

           class NAME VERSION : ATTRIBUTES... BLOCK

           class NAME;

           class NAME VERSION;

           class NAME VERSION : ATTRIBUTES...;

The class keyword declares a new package (see "Packages" in perlmod) that is intended to be a class. All the other keywords from the 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 you use a block, the body of the block contains the implementation of the class. If you use the statement form, the rest of the current scope or file is used up until the next class or package statement. πŸ“¦

A class declaration can optionally have a version number, just like the package keyword. It can also optionally have attributes. If you specify both, the version number must come first, before the attributes. No switching it up. πŸ™…β€β™€οΈ

class and package declarations are similar, but classes automatically get a constructor named new β€” you don't have to (and should not) write one. Also, inside the class BLOCK you're allowed to declare fields and methods. Slay. πŸ’…

🌱 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 method and ADJUST 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 creating 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 is 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 :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. 🎯

During a field initializing expression, the instance is not yet constructed and so the $self lexical is not available. However, the special __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 DifferentCustomField is constructed, the __CLASS__ expression in the base will yield the correct class name, and so invoke this overridden method instead. Iconic. πŸ‘‘

πŸ› οΈ 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 $self populated with the current object instance will automatically be created in the lexical scope of 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. 🀫

           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';
                   };
               }
           }

Methods can also be declared as lexical subroutines, using the 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 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's best to use the ->& 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

πŸŽ€ ATTRIBUTES πŸŽ€

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. ✨

πŸ›οΈ Class attributes

:isa

Classes may inherit from one superclass, by using the :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 :isa attribute may request a minimum version of the base class. As with 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 :isa attribute will attempt to require the named module if it is not already loaded. πŸ“¦

🌿 Field attributes

:param

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. 🚨

:reader

A field with a :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;

:writer

A field with a :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 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. ⚠️

πŸ› οΈ Method attributes

None yet. πŸ’€

πŸ¦‹ OBJECT LIFECYCLE πŸ¦‹

okay bestie so every object literally has a whole life story and we're gonna walk through it like it's a coming-of-age movie πŸ’–


🌱 Construction

Every object starts its lil journey with a constructor call, no cap. The constructor is always named new and you invoke it like a method call on the class name:

my $object = My::Class->new(%arguments);

While the object is being constructed, class fields get looked up in the %arguments hash and populated wherever they can be. it's giving "fill in the blanks but make it ✨classy✨".


πŸŽ€ Adjustment

Object adjustment is how you run arbitrary user-defined code during object construction. You do this by dropping code into ADJUST blocks. Every single time an object is constructed, its ADJUST blocks run β€” in the order they're declared, so order really does matter here bestie πŸ™ˆ

class WellAdjusted {
    field $x :param;
    ADJUST {
        say "Hello!";
    }
    ADJUST {
        say "x = $x";
    }
}

my $object = WellAdjusted->new(x => 42);
# Output:
#   Hello!
#   x = 42

ADJUST blocks are syntactically similar to BEGIN or INIT blocks β€” which, side note, only run once. But ADJUST blocks? Like methods, they get access to $self (a lexical variable holding the object being constructed) and all object fields created up to that point. so they're the main character and they know it πŸ’…


✨ Lifetime

Once the construction phase is done, the object is ready to be used. glow up complete πŸ¦‹

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'. iykyk πŸ”₯


πŸ’€ Destruction

An object is destroyed when the last reference to it goes away β€” just like with other data structures in Perl. rip boo, you had a good run 🫢


🚧 TODO 🚧

This feature is still experimental and very incomplete, bestie. Don't build your whole life on it yet. The following list gives an overview of features 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).

  • 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 (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.

  • More accessor generator attributes πŸ’…

Attributes to request that other kinds of accessor methods be generated for fields. Likely :writer.

class X {
    field $name :writer;
}

Equivalent to

class X {
    field $name;
    method set_name ($new) { $name = $new; return $self; }
}
  • Metaprogramming 🧠

An extension of the metaprogramming API (currently proposed by PPC0022 β€” https://github.com/Perl/PPCs/pull/25) 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.


πŸ’€ KNOWN BUGS πŸ’€

okay so these are the bugs that have been found in the experimental class feature. read them. respect them. do not act like you didn't see them 😭

πŸ‘‘ AUTHORS πŸ‘‘

  • Paul Evans
  • Bartosz Jarzyna

and that's the whole page bestie!! πŸ’– this one came from perl v5.42.3, dated 2026-08-03 β€” go forth and write slay classes, but maybe don't poke the segfaults, mwah πŸŽ€βœ¨

πŸ“¦ where this page comes from