Monks. Following a previous example I've written the following perfectly WORKING code in my Item class constructor.
However, I'd like to take the next obvious step while furthering my perl knowledge and replace the last if block with a hash lookup. i.e replace the follwoing:
*$name = $setter; and *$name = $getter;
with something like:
*$name = $accessors->{$name}
or *$name = ${$accessors->{$name}}
But after reading 'prelref' over and over and futzing with different combinations I keep coming up with undefined values and *$name not holding the reference to my built function.
i.e. no matter what I try I cant get $item->status() to work after refactoring. It works as is and builds the correct status() and team() methods but not if I try to do it using the lookup.
Whats the proper way to refactor the last block and make the symbolic references work?
package Item;
sub new{
...<make hash, bless, etc, etc>....
my $accessors = {
team => "getter",
status => "setter",
};
for my $name (keys %{$accessors}){
# Defines read-write access to a DB column.
my $setter = sub {
my $s = shift;
# Setting of value requested.
if( @_ ){
...<set value in database>...
...<other setter only code>...
$self->{$name} = $value;
}
return $self->{$name};
};
my $getter = sub {
my $s = shift;
if( @_ ){
carp("Attempting to set value $_[0] for read-only var
+$name!\n");
}
return $self->{$name};
};
no strict 'refs';
if( $accessors->{$name} eq "setter" ){
*$name = $setter;
}else{
*$name = $getter;
}
return $self;
}
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.