0

what are the differences between moose Perl and oop Perl ?

why we are using Moose Perl in place of oop Perl?

user1363308
  • 938
  • 4
  • 14
  • 33
  • Moose is just oop framework which does the same thing for oop in Perl but with fewer steps. – edem Apr 12 '13 at 15:52

1 Answers1

25

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:

  • Turns on strict and warnings for you
  • Sets up a constructor which validates that x and y are integers
  • Sets up (non-buggy) accessors and mutators for the x and y fields
  • Sets up a metaclass for introspection, and provides metaobjects as well

You 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.

friedo
  • 65,762
  • 16
  • 114
  • 184