Your implementation is not going to work in a threaded environment, as memory addresses will change after a clone. You will have to implement a CLONE method as well.

Or you could just use 5.10.x and use Hash::Util::FieldHash::fieldhash. Then the work needed in CLONE and DESTROY will be done for you, and you don't need refaddr either. Just use the reference itself as the hashkey.

Hash::Util::FieldHash makes Inside-Out Objects much easier to work with. With it, I would write your example as:

package MyMod; use strict; use warnings; use Carp; use Hash::Util::FieldHash qw[fieldhash]; fieldhash my %attr1; fieldhash my %attr2; my %hashrefs = ( attr1 => \%attr1, attr2 => \%attr2, ); sub new { my $class = shift; my %args = @_; my $self = bless do {\my $dummy}, $class; $attr1{$self} = $args{attr1}; $attr2{$self} = $args{attr2}; $self; } sub set { my ($self, $attr, $value) = @_; if (exists $hashrefs{$attr}) { $hashrefs{$attr}{$self} = $value } else { carp "Invalid attribute name $attr"; } } sub get { my ($self, $attr) = @_; if (exists $hashrefs{$attr}) { return $hashrefs{$attr}{$self} } else { carp "Invalid attribute name $attr"; return; } } 1;

In reply to Re^2: Prevent direct acces to object's attributes by JavaFan
in thread Prevent direct acces to object's attributes by vitoco

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.