Dynamic Accessor Methods · Sep 2, 10:33 PM by Dylan Doxey
So here I am writing this module which pulls a database record that is keyed by a topic keyword. And each accessor method was just a copy of the one preceding it, over and over. To make matters worse, each time there's a new topic added to the database am I to go an add yet another accessor method? Not.
Introducing the dynamic accessor method.
...
for my $topic (@topics) {
my $method_name = sprintf '%s::get_%s', __PACKAGE__, $topic;
my $method_rc = sub {
my $self = shift;
my $page_rh = $self->{db}->select_rh( {
from => 'content',
where_rh => {
topic => $topic,
},
} );
$page_rh->{text} //= $MT_STR;
return $page_rh->{text};
};
{
no strict 'refs';
*{$method_name} = $method_rc;
}
}
...
Anyone curious about my database interface?

Commenting is closed for this article.
