The Core class Feature
Introduced as experimental in Perl 5.38 (from the "Corinna" design). 5.40 added :reader and __CLASS__, and later releases keep extending it (e.g., :writer, lexical methods). Check perldoc perlclass for your version.
class Name; or class Name {... } class Child:isa(Parent) (single inheritance)
field $x;, field @list;, field %map; (truly private) field $x:param;, field $x:param(alt_name) = default;, //= and ||= defaults
:reader (5.40+); check newer releases for :writer method name {... }, method name($arg) {... } (signatures included) ADJUST {... } __CLASS__ (5.40+) Not yet (at 5.38/5.40)
Roles, DOES, attribute introspection (still planned) Objects are opaque (not blessed hashes). You can't reach into fields from outside.
Object::Pad (CPAN) provides the same model with roles and more features on older Perls.
use v5.38;
use experimental 'class'; # or: use feature 'class'; no warnings 'experimental::class';
class Point 1.0 { # class NAME VERSION BLOCK
field $x :param = 0; # :param = constructor argument
field $y :param = 0;
field @history; # private field (only visible in methods)
method x { $x }
method y { $y }
method move($dx, $dy) {
push @history, [$x, $y];
$x += $dx;
$y += $dy;
return $self; # $self is automatically available in methods
}
method to_string { "($x, $y)" }
}
class Point3D :isa(Point) {
field $z :param :reader = 0; # :reader generates a z() accessor (5.40+)
ADJUST { # runs during construction (like BUILD)
die "z must be numeric" unless $z =~ /^-?\d+(?:\.\d+)?$/;
}
method to_string { my $base = $self->SUPER::to_string(); $base =~ s/\)$/, $z)/; $base }
}
my $p = Point3D->new(x => 1, y => 2, z => 3);
$p->move(1, 1);
say $p->to_string; # (2, 3, 3)
say $p->z;