Logo

dev-resources.site

for different kinds of informations.

Perl Roles

Published at
1/14/2022
Categories
perl
programming
oop
role
Author
dragostrif
Categories
4 categories in total
perl
open
programming
open
oop
open
role
open
Author
10 person written this
dragostrif
open
Perl Roles

1. Roles Definition

A role is a set of methods that provide extra behavior to a class. Roles can't be used independently they need a class to consume them. Roles are a good alternative to inheritance.

2. A sample role

A role is declared in a *.pm file.

package Role::JSON;
use Moose::Role;

use JSON 'encode_json';

requires qw( data );

sub to_json {
  my $self = shift;

  return encode_json( $self->data() );
}

1;
Enter fullscreen mode Exit fullscreen mode

3. Consuming a role

In the previous example the Role::JSON requires
the consuming class to have a method named data().

package Foo;
use Moose;
with "Role::JSON";

sub data {
 my $self = shift;
 return { foo => 'bar' }; 
}

__PACKAGE__->meta->make_immutable;

1;
Enter fullscreen mode Exit fullscreen mode

Then you could just call the method defined in the role in your program:


my $obj = Foo->new();

print $obj->to_json();

# And that prints the following JSON
# { foo : 'bar' }

Enter fullscreen mode Exit fullscreen mode

4. Checking if class consumes a role

Because roles are not inherited you cannot use isa() to check if a class consumes a role instead you should use does():

$object->does("Role::JSON");
Enter fullscreen mode Exit fullscreen mode

5. Roles without Moose/Moo

Cpan module Role::Tiny allows you to use roles with vanilla OOP not just with Moose or Moo. Like Moose or Moo, Role::Tiny applies strict and warnings to the caller.

package Role::Foo;
use Role::Tiny;
sub data { 
 my $self = shift; 
 return { foo => 'bar' };
}
1;

package Bar;
use lib 'lib';
use Role::Tiny::With;
with  'Role::Foo';
....
1;
Enter fullscreen mode Exit fullscreen mode

Role::Tiny makes available to your role the following method modifiers: before, around and after.
In this example when $self->data is called the around block executes and you get JSON returned.

package Role::JSON;
use Role::Tiny;
use JSON 'encode_json';

requires qw( data );

around data => sub  {
  my $orig = shift;
  my $self = shift;

  return encode_json( $self->$orig() );
};  

Enter fullscreen mode Exit fullscreen mode

6. Compositional safety

Roles attempt to guarantee compositional safety. So, if two roles have the same method defined and you try to consume them in the same class, you will get an error message.

 Due to method name conflicts in roles ....
Enter fullscreen mode Exit fullscreen mode

Just remember that in order to trigger the error message you need to consume all the roles at once:

# good
package Foo;
use lib 'lib';
use Role::Tiny::With;
with  'Role::XML', 'Role::JSON';

# bad second method is ignored
package Foo;
use lib 'lib';
use Role::Tiny::With;
with  'Role::XML'; 
with  'Role::JSON';

Enter fullscreen mode Exit fullscreen mode

7. How to fix method collision

  • implement the methods yourself in your class, thus causing the corresponding role methods to be ignored

  • For Moose use the excludes key word

package Role::JSON;
use Moose::Role;

sub serialize { ... }

package Role::XML;
use Moose::Role;

sub serialize { ... }

package Foo;
use Moose;
with Role::Serializable::JSON,
     Role::Serializable::XML => { excludes => 'serialize' };
Enter fullscreen mode Exit fullscreen mode
  • For Role::Tiny use namespace::clean
package Role::XML;

use Role::Tiny;

sub serialize { my $self = shift; print 'test'  };
# serialize() will not be imported in the consuming class
use namespace::clean;

1;
Enter fullscreen mode Exit fullscreen mode

8. Bibliography

role Article's
30 articles in total
Favicon
A Quick Overview of Delivery Manager Role in the Modern Enterprise SDLC Process (Software Development Life Cycle)
Favicon
Liman MYS - Domain Eklentisi | Ağaç Yapısı Üzerinden Belirli Organizasyona Yetki Verme
Favicon
Liman MYS - Politikalar | OU'da Var Olan Politikaların Yeni OU'ya Eklenmesi
Favicon
** Navegando por las arenas del conocimiento: Habilidades para el Desarrollo Tecnológico: Una Odisea en el Desierto de Dune **🌕
Favicon
Editing an IAM Service Role, and Attaching Service Roles to AWS Resources
Favicon
Tech Job Hunting
Favicon
How to run commands remotely on an EC2 Instance with AWS Systems Manager
Favicon
supabase에 새 role 추가하기
Favicon
Data Engineering for Beginners: A Step-by-Step Guide
Favicon
How to view, assign and remove roles in Azure
Favicon
Create a cluster in Amazon EKS and install kubectl
Favicon
Decoding the Future: The Role of SAP on AWS Certification in Industry 4.0
Favicon
Why Architect Software?
Favicon
Securing Resource Provisioning Between Multiple AWS Accounts with IAM: Best Practices and Benefits
Favicon
Understanding the Role of an SEO Consultant: Is Hiring One Right for You?
Favicon
AWS IAM Services: A Comprehensive Guide to Secure Access Management
Favicon
Cross-Account Access to Amazon S3 using STS:AssumeRole
Favicon
Understanding the IT Business Analyst Role Real Quickly
Favicon
AWS de Dev pra Dev: Credentials e acesso programático - parte 2
Favicon
User Roles And Permissions Without Package Laravel 9
Favicon
Role And Permission In Laravel 9 Tutorial
Favicon
What is your role as RPA (Robotic process Automation) developer ?
Favicon
Laravel Api create Users,Posts with Role Permissions using Gates no packages
Favicon
Perl Roles
Favicon
Laravel Spatie Roles and Permissions Tutorial from Scratch
Favicon
Laravel 8 User Roles and Permissions Tutorial using Laratrust Package
Favicon
Authorize Atlas to Access your AWS Account
Favicon
Spot Instance Scenarios
Favicon
Laravel 7.x Role Based Authentication Tutorial
Favicon
Who is a Sr Software Engineer?

Featured ones: