http://qs321.pair.com?node_id=656240

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have a module implemented as an inside-out object, and I want to generically expose all of its properties (as read-only), via an accessor method. Following the naming conventions from Perl Best Practices, all properties are named %dbh_of, %csv_of, %working_dir_of, etc. As such, I wrote the following method:
sub get { my($self,$attr) = @_; my $return_val; # if valid attribute, assign it as a return value if($attr =~ m/\A\w+\z/) { my $eval_string = sprintf '$return_val = $%s_of{refaddr $self};', +$attr; eval $eval_string; } # otherwise, carp a warning else { carp("Invalid attribute '$attr'"); } return $return_val; }
The idea behind this is that, given a string value of the name of a property (such as 'working_dir'), it would return the value of that property for the current instance (the value of %working_dir_of{refaddr $self}). This is not working, however, as all I get back from the method is undefs. I've tried replacing the string eval with a symbolic reference, even though IIRC, this could be exploited if attr is provided a raw memory address:
if($attr =~ m/\A\w+\z/) { $return_val = ${$attr}{refaddr $self}; }
Even with this, I'm still getting undefs returned...Any idea what I'm doing wrong, or (better yet) is there a simpler and better way?