Moose (Perl)
Moose is an extension of the object system of the Perl programming language. Its stated purpose[1] is to bring modern object-oriented programming language features to Perl 5, and to make object-oriented Perl programming more consistent and less tedious. FeaturesMoose is built on ClassesMoose allows a programmer to create classes:
AttributesAn attribute is a property of the class that defines it.
RolesRoles in Moose are based on traits. They perform a similar task as mixins, but are composed horizontally rather than inherited. They are also somewhat like interfaces, but unlike some implementations of interfaces they can provide a default implementation. Roles can be applied to individual instances as well as Classes.
ExtensionsThere are a number of Moose extension modules on CPAN. As of September 2012[update] there are 855 modules in 266 distributions in the MooseX namespace.[2] Most of them can be optionally installed with the Task::Moose module.[3] ExamplesThis is an example of a class package Point;
use Moose;
use Carp;
has 'x' => (isa => 'Num', is => 'rw');
has 'y' => (isa => 'Num', is => 'rw');
sub clear {
my $self = shift;
$self->x(0);
$self->y(0);
}
sub set_to {
@_ == 3 or croak "Bad number of arguments";
my $self = shift;
my ($x, $y) = @_;
$self->x($x);
$self->y($y);
}
package Point3D;
use Moose;
use Carp;
extends 'Point';
has 'z' => (isa => 'Num', is => 'rw');
after 'clear' => sub {
my $self = shift;
$self->z(0);
};
sub set_to {
@_ == 4 or croak "Bad number of arguments";
my $self = shift;
my ($x, $y, $z) = @_;
$self->x($x);
$self->y($y);
$self->z($z);
}
There is a new This is the same using the use MooseX::Declare;
class Point {
has 'x' => (isa => 'Num', is => 'rw');
has 'y' => (isa => 'Num', is => 'rw');
method clear {
$self->x(0);
$self->y(0);
}
method set_to (Num $x, Num $y) {
$self->x($x);
$self->y($y);
}
}
class Point3D extends Point {
has 'z' => (isa => 'Num', is => 'rw');
after clear {
$self->z(0);
}
method set_to (Num $x, Num $y, Num $z) {
$self->x($x);
$self->y($y);
$self->z($z);
}
}
See also
References
External links |
Portal di Ensiklopedia Dunia