What is roles and composition in Perl?

roles, composition, Perl, object-oriented programming, code reuse, method delegation
Roles and composition in Perl are powerful concepts that enable code reuse and method delegation, enhancing object-oriented programming by allowing objects to share behavior seamlessly.

# Example of roles and composition in Perl

package MyRole {
    use Moose::Role;
    
    sub speak {
        my ($self) = @_;
        return "Hello from the role!";
    }
}

package MyClass {
    use Moose;
    with 'MyRole';

    sub greet {
        my ($self) = @_;
        return $self->speak();
    }
}

my $object = MyClass->new();
print $object->greet();  # Output: Hello from the role!
    

roles composition Perl object-oriented programming code reuse method delegation