Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create objects in Perl?

Tags:

syntax

oop

perl

Perl has OOP features, but they are somewhat rarely used. How do you create and use Perl objects with methods and properties?

like image 395
andrewrk Avatar asked Aug 11 '08 15:08

andrewrk


1 Answers

You should definitely take a look at Moose.

package Point;
use Moose; # automatically turns on strict and warnings

has 'x' => (is => 'rw', isa => 'Int');
has 'y' => (is => 'rw', isa => 'Int');

sub clear {
    my $self = shift;
    $self->x(0);
    $self->y(0);
}

Moose gives you (among other things) a constructor, accessor methods, and type checking for free!

So in your code you can:

my $p = Point->new({x=>10 , y=>20}); # Free constructor
$p->x(15);     # Free setter
print $p->x(); # Free getter
$p->clear();
$p->x(15.5);   # FAILS! Free type check.

A good starting point is Moose::Manual and Moose::Cookbook

If you just need the basic stuff you can also use Mouse which is not as complete, but without most of the compile time penalty.

like image 90
Pat Avatar answered Oct 02 '22 12:10

Pat