logo codesdope

More Moose


You will learn about polymorphism in this chapter. We use Moose::Role for this. Let's first look at the following example:

package Animal;

use Moose::Role;

requires qw( name food age );

1;
package Bark;

use Moose::Role;

sub bark{
  return "Bhoow bhoow";
}

1;
package Dog;

use Moose;

has name => (is => 'ro', isa => 'Str', default=>"xyz");
has food => (is => 'ro', isa => 'Str', default=>"Bread");
has age => (is => 'ro', isa => 'Int', default=>0);

with 'Animal', 'Bark';

1;
use strict;
use warnings;
use feature ':5.10';

use Dog;

my $obj = Dog->new;

if ($obj->DOES('Animal')){
  say "Dog is an animal";
  say $obj->bark();
}
Output
Dog is an animal
Bhoow bhoow

Now let's go through this code.

requires qw( name food age ); - It means that anything doing this role must have a name, food and age.

with 'Animal', 'Bark'; - The with keyword is used to apply roles to a class.

$obj->DOES('Animal') - DOES returns true if the class of the object has the role of 'Animal' in it.

Rest of the codes must be clear to you.

Download Our App.
BlogsDope App
Get it on Google Play
Doubt? Ask question
Close

Welcome.please sign up.

Close

Welcome.please login.