Alex Rivera | Logout

How do I define private or internal methods in object oriented Perl?

Asked 2009-11-14T14:33:30.227
9

I'm using Damian Conway's "inside-out" objects as described is his wonderful book Perl Best Practices to construct an object-oriented interface to a security system at my client. I'm coming across the need to use internal helper methods within my module that I would normally designate as "_some_method". However, this seems to break encapsulation since they can be called directly via the package name. Is there any way of making these methods truly private? As an example,

use SOD::MyOOInterface;

my $instance1 = SOD::MyOOInterface->new();
$instance1->_some_method;  #this produces an error: 
SOD::MyOOInterface::_some_method;   # this results in a 
                                    # successful method call 

Obviously I don't want the direct call of _some_method to succeed. Is there any way of guaranteeing this?

Edit
Report

1 Answer

8

Sort of. You can't hide a subroutine that's installed into the symbol table, but you can use a lexical variable to hold a reference to an anonymous subroutine:

package SOD::MyOOInterface;

my $some_method = sub { ... }

$some_method->();

Because $some_method is only visible in the file implementing the class, the subroutine can't be called externally. The drawback is that it can't be called as a method, it must be called as a function. If you want to use it as a method you'll have to pass the object reference explicitly:

$some_method->($obj, @args);
answered 2009-11-14T14:45:16.880

Your Answer