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:
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: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; }
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?if($attr =~ m/\A\w+\z/) { $return_val = ${$attr}{refaddr $self}; }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Generic accessor for inside-out objects...
by Joost (Canon) on Dec 10, 2007 at 21:47 UTC | |
by Anonymous Monk on Dec 10, 2007 at 22:00 UTC | |
by Joost (Canon) on Dec 10, 2007 at 22:15 UTC | |
by Anonymous Monk on Dec 10, 2007 at 22:19 UTC | |
by Joost (Canon) on Dec 10, 2007 at 22:49 UTC | |
Re: Generic accessor for inside-out objects...
by shmem (Chancellor) on Dec 10, 2007 at 22:41 UTC | |
Re: Generic accessor for inside-out objects...
by kyle (Abbot) on Dec 10, 2007 at 22:41 UTC | |
by EvanK (Chaplain) on Dec 11, 2007 at 15:46 UTC | |
by kyle (Abbot) on Dec 11, 2007 at 16:47 UTC | |
Re: Generic accessor for inside-out objects...
by parv (Parson) on Dec 10, 2007 at 22:12 UTC |
Back to
Seekers of Perl Wisdom