Something like this I'd guess:

sub new { my $class = shift; my $extends = $class->SUPER::new(@_); $extends->setFlyBehaviour( src::bo::CannotFly->new() ); $extends->setQuackBehaviour( src::bo::CanSqeek->new() ); my $self = { COLOR => undef, }; my @protected = qw/COLOR/; my @private = qw//; my $closure = sub { my $field = shift; if ( exists $self->{$field} ) { grep( /$field$/, @private ) and caller(0) eq __PACKAGE__ || confess "$field is private"; grep( /$field/, @protected ) and caller(0)->isa(__PACKAGE_ +_) || confess "$field is protected"; if (@_) { $self->{$field} = shift; } return $self->{$field}; } else { return $extends->( $field, @_ ); } }; bless( $closure, $class ); return $closure; } sub setColor { my $closure = shift; my $color = shift; &{ $closure }("COLOR", $color); } sub getColor { my $closure = shift; return &{ $closure }("COLOR"); }

Ok, I have to repeat the incantation to mark the private and protected fields as such... for as long as I want to go that far. Here I don't use privates so I could drop the @private and the grep for private fields. In fact I could drop the grep as well and just test on the name before calling confess.

It would be neat to have a cpan class that would do this automagically though...

--
if ( 1 ) { $postman->ring() for (1..2); }

In reply to Re^4: A quicker way to have protected and private fields? by gargle
in thread A quicker way to have protected and private fields? by gargle

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.