Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Private methods

by adrianh (Chancellor)
on Mar 09, 2003 at 22:45 UTC ( #241617=note: print w/ replies, xml ) Need Help??


in reply to Private methods

If you want to create a subroutine that only the Foo package can access, lexically scoped coderefs are the way to go. However, I can only think of a few situations where you really need to be that secretive.

I find that most of the time all I need is to prevent a subclass overriding the subroutine, in which case I would either calling it as a subroutine rather than a method, or specify the package of the method directly. For example:

package Foo; sub _init { shift->{foo} = 1 } sub new { my $class = shift; my $self = bless {}, $class; _init($self); $self; } package Bar; use base qw(Foo); sub _init { shift->{bar} = 2 } sub new { my $class = shift; my $self = $class->SUPER::new; _init($self); $self; }

or

package Foo; sub _init { shift->{foo} = 1 } sub new { my $class = shift; my $self = bless {}, $class; $self->Foo::_init; $self; } package Bar; use base qw(Foo); sub _init { shift->{bar} = 2 } sub new { my $class = shift; my $self = $class->SUPER::new; $self->Bar::_init; $self; }

gives us

package main; use Data::Dumper; print Dumper(Bar->new); __END__ $VAR1 = bless( { 'bar' => 2, 'foo' => 1 }, 'Bar' );


Comment on Re: Private methods
Select or Download Code
Re: Re: Private methods
by adrianh (Chancellor) on Mar 11, 2003 at 07:36 UTC

    ... and after Apocalypse 6 we have submethods & BUILD in perl 6:

    ... in Foo ... submethod BUILD { $.foo = 1 }; ... in Bar ... submethod BUILD { $.bar = 2 };

    I so want perl6 now :-)

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://241617]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (15)
As of 2015-07-02 13:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (40 votes), past polls