How to create a private / public variable and function using Moose?

I use Moose recipes and I still don’t see if I can create private variables and functions using this? Is it possible? If so, how do you create them with Moose?

+6
source share
2 answers

As Daxim points out, private methods are prefixed with "_". Since attributes (instance variables) generate getters methods (and if rw also sets 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 inside your class / instance and not set it externally. If the read access is too large, you can also mark it "private":

 has '_myvariable' => ( is => 'ro', writer => '_set_myvariable' init_arg => undef, # other options here ); 
+10
source

ID prefix with _ to denote function / variable, etc. like closed. This is described in perlstyle in the section on visibility in the middle of the document.

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

+10
source

Source: https://habr.com/ru/post/885792/


All Articles