in reply to OOP private functions
Generally speaking, you will want to call the _topsecretsort sub as a method, not as a function. The primary reason would be that _topsecretsort may need access to $self (perhaps so that it can call further methods), and even if the current implementation of _topsecretsort does not require access to $self, future rewrites of it may.
That said, I'd hesitate to call _topsecretsort a "private method". It is not a private method in the same sense that programming languages with true privacy would understand it. _topsecretsort can be called and overridden by superclasses, and by code entirely external to the class. I think the best term for this sort of sub would be an "undocumented method", not a "private method".
(In fact, getting back to whether the sub should be called as a function or as a method... the one advantage of calling the sub as a function instead of a method, would be that it would prevent superclasses from accidentally or deliberately overriding it.)
The best way to approximate true private methods in Perl is to use coderefs:
my $_topsecretsort = sub { my $self = shift; my ($x, $y) = @_; return 42; }; sub count_sorted_foobars { my $self = shift; my @results = $self->$_topsecretsort('foo', 'bar'); return scalar(@results); }
In Moops I've even created a shortcut for this pattern:
use Moops; class FooBar { method my $_topsecretsort ($x, $y) { return 42; } method count_sorted_foobars () { my @results = $self->$_topsecretsort('foo', 'bar'); return scalar(@results); } } say FooBar->new->count_sorted_foobars;
|
|---|