Moose (Perl) - Examples

Examples

This is an example of a class Point and its subclass Point3D:

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 set_to method in the Point3D class so the method of the same name defined in the Point class is not invoked in the case of Point3D instances. The clear method on the other hand is not replaced but extended in the subclass, so both methods are run in the correct order.

This is the same using the MooseX::Declare extension:

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); } }

Read more about this topic:  Moose (Perl)

Famous quotes containing the word examples:

    In the examples that I here bring in of what I have [read], heard, done or said, I have refrained from daring to alter even the smallest and most indifferent circumstances. My conscience falsifies not an iota; for my knowledge I cannot answer.
    Michel de Montaigne (1533–1592)

    It is hardly to be believed how spiritual reflections when mixed with a little physics can hold people’s attention and give them a livelier idea of God than do the often ill-applied examples of his wrath.
    —G.C. (Georg Christoph)

    Histories are more full of examples of the fidelity of dogs than of friends.
    Alexander Pope (1688–1744)