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

Class::Plain provides a class syntax for the hash-based Perl OO.

Usage

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;

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";
  }
}
 
my $point3d = Point3D->new(x => 5, y => 10, z => 15);
$point3d->describe;

See also the Class::Plain document and the cookbook.

Comment of First Release

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

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 .

And the existing modules for OO. Moo/Moose, Mojo::Base, Class::Accessor, Class::Accessor::Fast.

"Is my assumption correct?" I tried to create a module it was called Class::Plain.

I copied Object::Pad, and reduced the code except for the class, field, method keywords, and the internal data structure is changed from lexical variables to a hash reference(This contains a little lie because the hash reference is created dynamically).

And I completed the implementation of Class::Plain and released it to CPAN.

Comments are welcome!


2 Comments

The inclusion of a Cookbook (https://metacpan.org/release/KIMOTO/Class-Plain-0.04/source/lib/Class/Plain/Document/Cookbook.pm) is a fine example for others to emulate.

Leave a comment

About Yuki Kimoto

user-pic I'm Perl Programmer. I LOVE Perl. I want to contribute Perl community and Perl users.