The way to create Class with only Perl core language.

Do you know that Perl have enough object-oriented features in core language?

Not necessarily you need to use CPAN module to do object-oriented programing.

I write the entry "The way to create Class with only Perl core language".

The way to create Class with only Perl core features

package Point;

sub new {
   my $class = shift;

  my $self = {
    x => 0,
    y => 0,
    @_,
  };
  
   bless $self, $class;

  return $self;
}

sub x { shift->{x} }
sub y { shift->{y} }

 

my $point = Point->new(x => 1, y => 2);

my $x = $point->x;
my $y = $point->y;

In fact, which do you need

1. simple object-oriented programing

or

2. advanced object-oriented programing

in your job?

8 Comments

We use advanced OOP at work: Moose with traits, roles, coercions. We might need to switch some parts to Moo for better performance, but going back to bless is not an option here.

I've written a lot of code like that over the years. For simple classes, it works, and when I'm prototyping things I often use that approach.

However, having to write accessors, including code for validation, etc., becomes a time sink. Lazy attribute evaluation is sometimes critical to an application's performance, and I find I use that (via Moo) quite a bit. I've also become very fond of roles (in the Role::Tiny sense) and use them quite a bit.

So, I'd say the current core object approach has its place, but for any code which I know will last more than a few prototyping iterations I reach for a more sophisticated model.

This was standard early way to do things from many years ago. 1980~90s. Now days we would call it Old Shcool.

https://www.perl.com/article/25/2013/5/20/Old-School-Object-Oriented-Perl/

I have had to do above in so called closed systems some time ago even wrote a module(Orignal) to help me out is such situations.

If I had to work on such a closed system today with and it had up to date perl I would go with Class::Struct as that is part of core

Hmm, looks like you're right. I thought this worked reliably.

Leave a comment

About Yuki Kimoto

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