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

One Pingback/Trackback

6 thoughts on “Proper usage of the roles in Perl”

  1. The next release of Moo should include documentation about this. Fitz Elliott has written up some examples of this technique, as well as using namespace::clean.

  2. This is relevant to Perl packages in general; if you put the ‘use’ statements outside the package declaration, the functions they export will be visible in the file scope, but won’t show up as methods of the package elsewhere. Which means you don’t need namespace::clean if you’re careful.

    1. Won’t they be available through the main:: namespace then? That seems just as bad, or worse, as now the entire runtime environment can access those functions.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">