PERLCLASS(1perl)

πŸ“¦
version 5.44.0 Β· 2 versions
, in arch rolling

✨ NAME ✨

perlclass β€” the whole entire reference for Perl's <hotpink>class</hotpink> syntax, bestie πŸ’… no cap


πŸ¦‹ 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 document is literally the syntax reference for Perl's <hotpink>class</hotpink> feature β€” the one that hands you native keywords for object-oriented programming. we are not playing around here. πŸ’–

πŸŽ€ History πŸŽ€

so since Perl 5, object support has revolved around the concept of blessing references with a package name (peep "bless REF,CLASSNAME" in perlfunc). a reference like that could then be used to call subroutines from the package it was blessed with β€” or any of its parents, queen behavior πŸ‘‘. this system, while honestly bare-bones, was flexible enough to let the community build multiple more advanced, community-driven systems for object orientation. for more info, go read perlmod and perlobj, they're right there bestie.

the <hotpink>class</hotpink> feature is a core implementation of a class syntax β€” like, similar to what you'd find in other programming languages ✨. it is not a wrapper around bless. it is a completely new system, built right into the perl interpreter. iconic. periodt. πŸ’…


πŸ’œ KEYWORDS πŸ’œ

enabling the <hotpink>class</hotpink> feature lets you use the following 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 <hotpink>class</hotpink> keyword declares a new package (see "Packages" in perlmod) that is intended to be a class 🫢. every other keyword from the <hotpink>class</hotpink> feature should be used within the scope of this declaration, okay?

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 gets used, up until the next <hotpink>class</hotpink> or <hotpink>package</hotpink> statement. slay.

a <hotpink>class</hotpink> declaration can optionally have a version number, similar to the <hotpink>package</hotpink> keyword. it can also optionally have attributes. if you're doing both, the version number must come first, before the attributes. order matters bestie, don't test me 🌸

class and package declarations are similar, but classes automatically get a constructor named new β€” you don't have to write one and like, should not write one πŸ™ˆ. also, inside the class BLOCK you're allowed to declare fields and methods. that's the whole point.

πŸ“ 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 <hotpink>method</hotpink> and ADJUST blocks ✨. each class instance gets its own storage of fields, totally independent of other instances. no sharing, no drama.

a field behaves like a normal lexically scoped variable. it has a sigil and it's private to the class (though creating an accessor method will make it accessible from the outside, iykyk). the main difference? different instances access different values in the same scope. wild, right?

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 one's present, the expression gets evaluated within the constructor of each object instance πŸŽ€. during each evaluation, the expression can use the value of any previously-set field, plus any other variables in scope.

class WithACounter {
    my $next_count = 1;
    field $count = $next_count++;
}

when combined with the <hotpink>:param</hotpink> field attribute, the defaulting expression can use any of the =, //= or ||= operators πŸ‘‘:

  • = β€” applies whenever the caller did not pass the corresponding parameter to the constructor at all.
  • //= β€” also applies if the caller did pass the parameter, but the value was undef.
  • ||= β€” applies if the value was false.

during a field initializing expression, the instance is not yet constructed, so the $self lexical is not available 😭. however, the special <rainbow>__CLASS__</rainbow> token may be used to grab the name of the class being constructed β€” for example, to invoke class methods on it and help construct values for fields.

class WithCustomField {
    use constant DEFAULT_X => 10;
    field $x = __CLASS__->DEFAULT_X;
}

this lets subclasses 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 it'll invoke this overridden method instead. main character energy fr fr ✨

πŸ’… 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 <hotpink>method</hotpink>. free real estate.

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 <hotpink>->&</hotpink> operator πŸ’…. this bypasses method lookup by name, and directly invokes a lexical subroutine as if it was a method. chef's kiss.

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 <hotpink>:isa</hotpink> 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. no field hand-me-downs, sorry bestie 😭

the <hotpink>:isa</hotpink> 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 <hotpink>:isa</hotpink> attribute will attempt to <hotpink>require</hotpink> the named module if it's not already loaded. it's proactive like that ✨

πŸŽ€ Field attributes πŸŽ€

🌸 :param

a scalar field with a <hotpink>:param</hotpink> 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's 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, it becomes optional. flexible queen ✨

πŸ’– :reader

a field with a <hotpink>:reader</hotpink> 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 too πŸ‘‘. 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 itself had been placed in scalar context. no cap.

field @users :reader;
...

scalar $instance->users;

πŸ¦‹ :writer

a field with a <hotpink>:writer</hotpink> 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, those will have to be created manually, bestie.

🌟 Method attributes 🌟

None yet.

to be continued… 🌸

πŸ’– OBJECT LIFECYCLE πŸ’–

🐣 Construction

Okay so every object starts its lil life with a constructor call. The constructor is always named new, and you call it like a method on the class name:

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

While the object is being constructed, class fields get looked up in that %arguments hash and populated wherever that's possible. Cute, right? πŸ’…

✨ Adjustment

Adjustment is the glow-up moment: it's how you run arbitrary user-defined code during object construction. You do it by dropping code into ADJUST blocks. Every single time an object is constructed, its ADJUST blocks run β€” and they run in the order they were declared. No queue-jumping allowed. πŸŽ€

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

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

ADJUST blocks look syntactically like BEGIN or INIT blocks β€” but those only run once, bestie, whereas ADJUST blocks are giving methods energy: they can see $self (a lexical variable holding the object currently being constructed) plus every object field created up to that point. Obsessed. 🌸

πŸ•°οΈ Lifetime

Once construction wraps up, the object is ready to be used. Main character era. πŸ‘‘

Call blessed (Scalar::Util::blessed or builtin::blessed) on the object and you get back the name of the class. Call reftype (Scalar::Util::reftype or builtin::reftype) and you get the string 'OBJECT'. That's it, that's the vibe check. πŸ”₯

πŸ’€ Destruction

An object gets destroyed when the last reference to it goes away β€” exactly like every other data structure in Perl. Rip bozo, you had a good run. πŸ™ˆ


🚧 TODO 🚧

Fair warning: this feature is still experimental and very incomplete. Here's the rundown of stuff that's still to be added or changed:

  • Roles β€” some syntax for declaring a role (probably a role keyword), plus something for consuming a role into a class (probably a :does() attribute).
  • Parameters to ADJUST blocks β€” some syntax for declaring that an ADJUST block can consume named parameters, which then become part of the class constructor's API. This might take inspo from 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 β€” rn every ADJUST block gets wrapped in its own CV (subroutine) that's 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 too, merging them all into a single CV per class. Result? Way faster to invoke if a class has more than one of them. ✨
  • 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 for out-of-core modules to interact with the class system, including an ability for them to provide new class or field attributes.

πŸ’€ KNOWN BUGS πŸ’€

These unresolved bugs are still living rent-free in the experimental class feature:

Bestie. Please. Read those three again. There are real, unresolved, crash-y bugs in here β€” this is experimental for a reason. 🫢

πŸ‘‘ AUTHORS πŸ‘‘

  • Paul Evans
  • Bartosz Jarzyna

That's a wrap, babe πŸ’– β€” this page is from perl v5.44.0, dated 2026-10-17, and the page itself is PERLCLASS(1perl). Slay, go write some classes. βœ¨πŸ¦‹πŸŒΈ

πŸ“¦ where this page comes from
  • arch rolling: perl 5.44.0-1 Β· Artistic-1.0-Perl AND GPL-1.0-or-later
  • πŸ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms