Private Methods
There is one way to invoke a method so that Perl ignores inheritance
altogether. If instead of a literal method name you specify a simple
scalar variable containing a reference to a subroutine, then the
subroutine is called immediately. In the description of UNIVERSAL–>can in
the previous section, the last example invokes all overridden methods
using the subroutine’s reference, not its name.
An intriguing aspect of this behavior is that it can be used to implement private method calls. If you put your class in a module, you can make use of the file’s lexical scope for privacy. First, store an anonymous subroutine in a file-scoped lexical:
# declare private method
my $secret_door = sub {
my $self = shift;
...
};Later on in the file you can use that variable as though it held a method name. The closure will be called directly, without regard to inheritance. As with any other method, the invocant is passed as an extra argument.
sub knock {
my $self = shift;
if ($self–>{knocked}++ > 5) {
$self–>$secret_door();
}
}This enables the file’s own subroutines (the class’s methods) to invoke a method that code outside that lexical scope cannot access.
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