Private and Public
By default, all methods and attribute accessors are public methods, so they can be called anywhere. You can also declare private methods or accessors, which can be called only within the class where they’re defined, or from certain trusted classes. A private method is declared with a colon at the start of the name:
method :inaccessible ($self: $value) { . . . }A private attribute is declared with a colon in place of the dot (.) in the name:
has $:hidden;
You call a private method or accessor with a colon in the call:
$object.:hidden(42);
The attribute
variable
($:name or $.name) is never
accessible outside the class, whether the attribute is public or
private.
At first glance this might look like nothing more than the
“encapsulation by convention” of
Perl 5. It’s actually much more than that. The colon
implicitly sets a private trait on the method or
attribute. The encapsulation is enforced by the interpreter. An
external call to a private method will fail as if the method simply
didn’t exist. External queries to the package symbol
table for private methods also fail.
Only public methods are inherited by a derived class, but inherited public methods can call private methods from their own class. Private methods and attributes in a role are private to the composed class, as if they were defined in that class.
The one loophole in private methods is that a class can declare that
it trusts certain other classes to allow those classes to access its private methods. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access