First we start with your basic "TextClass" class:
Note the with 'PrettyPrint'; That is the module which contains the role we will add.package TextClass; use Moose; has 'text' => ( is => 'rw', isa => 'Str', ); with 'PrettyPrint'; no Moose; __PACKAGE__->meta->make_immutable; 1;
We make another module to implement the "prettyprint" role:
The prettyprint sub from this module will now become a method in your 'TextClass' class or any other class that provides a text method. That is what the requires 'text' takes care of. Use this role in another class that doesn't provide the text method and it will complain and end the compilation of your script.package PrettyPrint; use Moose::Role; requires 'text'; sub prettyprint { my $self = shift; print "So handsome:\n\t", $self->text, "\nYeah, sure!\n"; $self; } 1;
As you see, the methods in your Role-module have access to all the public methods of your object, even those which are provided auto-magically by Moose itself, such as the getters and setters, in this case the text method.
Using all this now is standard:
Output:use Modern::Perl qw/2014/; use lib 'D:/Perl/scripts'; # or wherever you have saved the modules use TextClass; my $person = TextClass->new( text => q/I'm CountZero/ ); $person->prettyprint;
Note, that a Role isn't a class: it cannot be instantiated on its own, it will not provide its own objects. Rather it is a bunch of subroutines that get directly included in your basic class without any intermediary object. So you do not do $text->PrettyPrint::prettyprint or $text->PrettyPrintObject->prettyprintSo handsome: I'm CountZero Yeah, sure!
Update: clarified about adding a Role module.
CountZero
A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James
My blog: Imperial DeltronicsIn reply to Re: Moose attribute modification
by CountZero
in thread Moose attribute modification
by learning.moose
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |