package Shape;
use Moose;
has color => ( # an attribute called 'color'
is => 'rw', # creates an accessor for the color
isa => 'Str', # and it's a string
);
package Circle;
use Moose;
extends 'Shape'; # Circle isa Shape
has radius => ( is => 'rw', isa => 'Num' );
sub area {
my $self = shift;
return 3.141 * $self->radius ** 2
}
package Rectangle;
use Moose;
extends 'Shape'; # Rectangle isa Shape
has width => ( is => 'rw', isa => 'Num' );
has height => ( is => 'rw', isa => 'Num' );
sub area {
my $self = shift;
return $self->width * $self->height;
}
package main;
use strict;
use warnings;
my $r = Rectangle->new(height => 2, width => 2.5, color => 'green');
my $c = Circle->new(radius => .5, color => 'yellow');
printf "My %s is %s and has an area of %0.2f\n", ref $_, $_->color, $_
+->area
for $r, $c;
$c->radius(1); # The circle is now twice the size
printf "My new Circle is %s and has an area of %0.2f\n", $c->color, $c
+->area
Moose just makes it so quick and easy. Of course, Moose can do so much more, but that's what the documentation is for.
(Yes. I know. Roles would have been better)
|