Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you create private/public variable and functions using Moose?

Tags:

oop

perl

moose

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?

like image 654
Gaurav Dadhania Avatar asked Apr 13 '11 06:04

Gaurav Dadhania


1 Answers

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
);
like image 147
nxadm Avatar answered Sep 20 '22 13:09

nxadm