DEV Community

Yuki Kimoto - SPVM Author
Yuki Kimoto - SPVM Author

Posted on

Class::Plain - Class Syntax for Hash-Based Perl OO

Class::Plain was released at 2022-09-22.

use Class::Plain;

class Point {
  field x;
  field y;

  method new : common {
    my $self = $class->SUPER::new(@_);

    $self->{x} //= 0;
    $self->{y} //= 0;

    return $self;
  }

  method move {
    my ($x, $y) = @_;

    $self->{x} += $x;
    $self->{y} += $y;
  }

  method describe {
    print "A point at ($self->{x}, $self->{y})\n";
  }
}

my $point = Point->new(x => 5, y => 10);
$point->describe;
Enter fullscreen mode Exit fullscreen mode

Inheritance:

class Point3D : isa(Point) {
  field z;

  method new : common {
    my $self = $class->SUPER::new(@_);

    $self->{z} //= 0;

    return $self;
  }

  method move {
    my ($x, $y, $z) = @_;

    $self->SUPER::move($x, $y);
    $self->{z} += $z;
  }

  method describe {
    print "A point at ($self->{x}, $self->{y}, $self->{z})\n";
  }
}
Enter fullscreen mode Exit fullscreen mode

I'm strongly interested in Perl OO. I study Corinna and Object::Pad now.

A few weaks ago, I wondered "These class syntax can be applied to the traditional Perl hash-based OO modules. The syntax can be used with the all existing modules".

I remembered many OO modules. Net::FTP, IO::Socket::INET, IO::Socket::IP, LWP::UserAgent, HTTP::Tiny, XML::Simple, Data::Page, CGI, Digest::MD5, Digest::SHA, Mojolicious, Catalyst, DBIx::Class etc .

Class::Plain - Class Syntax for Hash-Based Perl OO

Oldest comments (1)

Collapse
 
jonasbn profile image
Jonas Brømsø

This is indeed nice 🤩