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



Short URL:

One Pingback/Trackback

  • Graham Knop

    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.

    • without namespace::clean and with a good attention, user can really select what they want to export from their methods, and what they want to keep private.

  • dotandimet

    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.

    • ether

      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.

      • dotandimet

        You’re right. That sucks. 🙁

  • Pingback: Planet Moose - December 2013 | Toby Inkster []()