I'm writing an object oriented module, and I wanted to be able to emulate c++'s protected method. That is, the method may be called by its own object, or an object that inherits from it. But it should not be usable otherwise.
I came up with this. It uses the __PACKAGE__ symbol to find out what package the method is located in. Maybe somebody has a better way, or can tell me if something is wrong with what I'm doing?
This seems like something a lot of people would want to do, and a rather simple solution, so please don't get upset with me if somebody else has already come up with it before me.
package foo; sub whatever { my $self = shift; unless ( UNIVERSAL::isa( $self, __PACKAGE__ ) ) { die( "Can't do that!" ); } ... }

Replies are listed 'Best First'.
(Ovid) Re: Make an object method "protected"
by Ovid (Cardinal) on Jan 26, 2002 at 04:58 UTC

    I think this is an interesting idea, but I'm not sure I care for it. OO programming in Perl basically has the caveat "opening the box voids the warranty". However, if you're willing to void the warranty, open the box (of course, most who will, shouldn't :).

    However, if you can think of a reason why you would want this, you might want to check out Attribute::Protected, on the CPAN.

    Cheers,
    Ovid

    Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.