isn't there a danger $self->{'JOKE'} is already in use?

Indeed. One way of avoiding this is to use your own package name in the hash key, to ensure a little more uniqueness:

my $package = __PACKAGE__ . ':'; sub set_joke { my $self = shift; $self->{$package.'JOKE'} = shift; } sub get_joke { my $self = shift; return $self->{$package.'JOKE'}; } sub say_joke { my $self = shift; print $self->get_joke, "\n"; }

This technique can only get you so far though - with some classes it's not enough, so the inside-out object technique explained by JavaFan is necessary.

As an example, imagine an EmailHeaders class where each hash key represents an e-mail header (To, From, Subject, etc). You want to subclass it and store some additional information which is not an e-mail header. But any key you add to the hash will be interpreted as another e-mail header by the parent class. Here you really would need to use inside-out objects.

perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

In reply to Re: avoiding overwriting variables in an inherited class by tobyink
in thread avoiding overwriting variables in an inherited class by whatnext156

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.