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?
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.