Perhaps the problem is somewhere else in your code. Filling in the blanks a little, it seems to work for me.

package Foo; use Scalar::Util qw( refaddr ); use Carp; my %a_of; my %b_of; sub new { my $self = \do{my $x}; bless $self, __PACKAGE__; $a_of{ refaddr $self } = 'a: ' . rand; $b_of{ refaddr $self } = 'b: ' . rand; return $self; } sub puke { my $self = shift; print $a_of{ refaddr $self }, "\n"; print $b_of{ refaddr $self }, "\n"; return; } sub get { # pasted from OP } package main; my $o = Foo->new(); $o->puke(); print 'a --> ', $o->get('a'), "\n"; print 'b --> ', $o->get('b'), "\n"; print 'c --> ', $o->get('c'), "\n"; __END__ a: 0.917827691956521 b: 0.0455599141746177 a --> a: 0.917827691956521 b --> b: 0.0455599141746177 Use of uninitialized value in print at /home/kyle/perlmonks.pl line 58 +. c -->
If you're trying to write one get method in some other package and import it into each inside-out class, that won't work for the reasons Joost has already mentioned.

Instead, maybe you should use the access methods available on the object. I did something like that in Make an inside-out object look hash-based using overload..

sub FETCH { my ($self, $key) = @_; my $getter = "get_$key"; return $self->$getter(); }

This way, you don't expose any private attributes, and you go through the proper access method, which might have some code in it more complicated that returning the attribute raw.


In reply to Re: Generic accessor for inside-out objects... by kyle
in thread Generic accessor for inside-out objects... by Anonymous Monk

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.