6

I am going through the Moose recipes and I still cannot see if I can create private variables and functions using it? Is it possible? If yes how to create them with Moose?

Gaurav Dadhania
  • 5,167
  • 8
  • 42
  • 61
  • 2
    You can take a look at MooseX::Privacy if you like, it is an extension to accomplish this. However, the private methods are not truly private since they will die instead of just being skipped in the dispatch. – Stevan Little Apr 13 '11 at 13:20

2 Answers2

10

Prefix an identifier with an _ to mark the function/variable etc. as private. This is documented in perlstyle in the section about scope, about in the middle of the document.

This is respected by sane programmers and some tools (source parsers/documentation), but not enforced by the compiler. See perlmodlib#NOTE.

daxim
  • 39,270
  • 4
  • 65
  • 132
10

Like daxim points out, private methods have the "_" prefix. Because attributes (instance variables) generate getters methods (and if rw also setters methods) out of the box, you should do this:

has 'myvariable' => (
    is       => 'ro',
    writer   => '_myvariable',
    init_arg => undef,
    # other options here
);

This way you can set this attribute within your class/instance and it's not settable from outside. If read-only access is too much, you can also mark it "private":

has '_myvariable' => (
    is       => 'ro',
    writer   => '_set_myvariable'
    init_arg => undef,
    # other options here
);
nxadm
  • 2,079
  • 12
  • 17