Perl has OOP features, but they are somewhat rarely used. How do you create and use Perl objects with methods and properties?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With