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?
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.