Proper usage of the roles in Perl

For everyone who doesn’t know it yet, you have to take care where you use “Moo::Role” (or Mouse::Role or Moose::Role).

Moo::Role will export all methods that is declared after his declaration.

Let me show an example :

If you do :

and in your class :

You will have those methods injected :

  • compute_my_array

But also

  • first
  • max
  • min

and it is not always wanted.

To fix it, declare ‘Moo::Role’ after the methods you wouldn’t want to be exported.

Example :

This will not export the methods ‘first’, ‘max’, ‘min’, ‘_my_private_sub’.

But it will export ‘public_method’ and the ‘_my_private_sub’ will works inside your class, because it is linked on compilation time.

Take care, if your private method is a sub that take ‘$self’, so a private method instead of a private sub, you have to call it like this :

Instead of

Enjoy

Celogeek

Short URL: http://sck.pm/WVO