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;