in reply to perl OO private methods

Yes, you can. But it's not entirely straightforward, and does it really matter? Perl has a convention that thou shalt not call methods outside your package that start with an underscore. But, if you know what you're doing, you still can. After all, the module author may be wrong and that function might really be needed. I know I've been on both ends of that before: both needing a function that was deemed private (started with a leading underscore), and marking a function private with the underscore that was later needed elsewhere. So it's nice that perl doesn't shackle the developer.

If you really need to, you can do something like this in your SOD::MyOOInterface package (or wherever you want the private method):

my $_some_method = sub { # method here. }; sub externalised_method { #... $_some_method->(@some_args); # or $self->$_some_method(@some_args); #... }
Because it's an anonymous function, no one who can't see the variable that holds its reference will be able to call it. But because it's a lexical to the current package, only methods/functions in the current package can see the variable, thus making it effectively hidden to anyone else: private.

Now, if you want protected equivalent, I don't know how to do that ... but, again, don't: that's not the perlish way.

Replies are listed 'Best First'.
Re^2: perl OO private methods
by ennuikiller (Acolyte) on Nov 14, 2009 at 17:27 UTC
    thanks very much!
Re^2: perl OO private methods
by pemungkah (Priest) on Nov 16, 2009 at 03:57 UTC
    You could simulate a protected method by having the method check caller() and die if the caller's not in the same package. You'd also need to use merlyn's trick to hide the method from anyone else; if it were allowed to live in the symbol table then it would be easy to swizzle it to a replacement unprotected version.

    Generally speaking, Perl programmers are willing to abide by the APIs: if you call a private method, then you're assuming the maintenance burden for it. So: don't bother. Document as internal use only and subject to change.