Sorry about the confusion about protected and private. I've came up (thanks to the replies) with the following 'system' to use.
package Base;
# Base class to experiment with private and protected methods
use warnings;
use strict;
use Carp;
sub new {
my $type = shift;
my $class = ref $type || $type;
my $self = {
TEXT => undef,
SECRET => undef,
NOTSOSECRET => undef,
};
my $closure = sub {
my $field = shift;
if (@_) { $self->{$field} = shift; }
return $self->{$field};
};
bless ($closure,$class);
return $closure;
}
# a public accessor to set TEXT
sub text { &{ $_[0] }("TEXT", @_[1 .. $#_]) }
# a private accessor to set SECRET
sub private {
caller(0) eq __PACKAGE__ || confess "private method";
&{ $_[0] }("SECRET", @_[1 .. $#_]);
}
# a public accessor to set SECRET by means of the private method
sub secret {
private($_[0],@_[1 .. $#_]);
}
# a protected accessor to set NOTSOSECRET
sub protected {
caller(0)->isa(__PACKAGE__) || confess "protected method\n";
&{ $_[0] }("NOTSOSECRET", @_[1 .. $#_]);
}
1;
package Inherit;
# Inherit class to experiment with private and protected methods
use warnings;
use strict;
use Base;
use vars qw(@ISA);
@ISA = qw(Base);
sub inheritSecret {
$_[0]->private(@_[1 .. $#_]);
}
sub inheritNotSoSecret {
$_[0]->protected(@_[1 .. $#_]);
}
1;
The main routine that calls all:
#!/usr/bin/perl
use warnings;
use strict;
use Base;
use Inherit;
my $base = Base->new();
$base->text("hello");
print $base->text . "\n";
my $inherit = Inherit->new();
$inherit->text("howdy");
print $inherit->text . "\n";
$base->secret("secret");
print $base->secret . "\n";
# this will get us an error saying private method
#$inherit->inheritSecret("verySecret");
#print $inherit->inheritSecret . "\n";
# impossible to access protected directly
#$inherit->protected("notsosecret");
#print $inherit->protected . "\n";
# access to NOTSOSECRET by means of a protected method
$inherit->inheritNotSoSecret("notsosecret");
print $inherit->inheritNotSoSecret . "\n";
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.