what are the differences between moose Perl and oop Perl ?
why we are using Moose Perl in place of oop Perl?
what are the differences between moose Perl and oop Perl ?
why we are using Moose Perl in place of oop Perl?
Moose Perl is OO Perl. Moose is an object framework built on top of the Perl 5 OO system.
What Moose gives you is a large number of tools to make OO Perl easier to use and more robust. Perl's object system is very bare-bones; it lets you do pretty much whatever you want, which is very powerful, but it also means you have to do everything yourself. For example, here's how you might implement an object to represent a point in a 2D plane in pure OO Perl.
package Point;
use strict;
use warnings;
use Carp 'croak';
sub new {
my $class = shift;
my %args = @_;
# do a lot of complex and potentially buggy validation here
# to make sure you have both an X and a Y coordinate, that
# they're both numbers, etc.
return bless \%args, $class;
}
Now we need to make some accessors and mutators
sub x {
my $self = shift;
my $val = shift;
$self->{x} = $val;
}
The above code is buggy. Do you know the reason(s) why? We also have to duplicate this for the y
parameter. We can copy and paste the code, or at least alias the symbol to avoid the C&P.
In Moose, this definition is just the following:
package Point;
use Moose;
has 'x' => (is => 'rw', isa => 'Int');
has 'y' => (is => 'rw', isa => 'Int');
What this does:
strict
and warnings
for youx
and y
are integersx
and y
fieldsYou get all that (and actually a lot more) for free in just four lines of code.
If you're not already familiar with how Perl OO works, I recommend reading (and then re-reading) the Perl OO Tutorial.
Then, start reading about Moose. A great starting point is the Moose::Manual POD.