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

package Bark;

use Moose::Role;

sub bark{
  return "Bhoow bhoow";

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';

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();
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.

Doubt? Ask question