Home > Archive > PERL Beginners > February 2006 > Generation of method names
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
Generation of method names
|
|
| Klaus Jantzen 2006-02-24, 6:57 pm |
| Hi,
to read a record from a database I generated a list of the column names
(@fields).
The get/set methods of the record class are constructed like "set+name
of column" e.g. getDate, setAmount.
After the DB-connect I would like to automatically generate the name of
the appropriate
set-method in order to reduce the typing :) :
while (my $hrRes = $sth->fetchrow_hashref)
{
foreach (@fields)
{
$self->"set".$_($hrRes->{$_});
# resulting in e.g. $self->setDate($hrRes->{'Date'}) or
# $self->setAmount($hrRes->{'Amount'})
}
}
How can I accomplish that (if at all)?
Thank you for yor help.
--
K. Jantzen
*
* <http://www.jantzen-software.de>
| |
| Ricardo SIGNES 2006-02-26, 9:56 pm |
| * Klaus Jantzen <kdjantzen@t-online.de> [2006-02-24T16:09:10]
> After the DB-connect I would like to automatically generate the name of the
> appropriate set-method in order to reduce the typing :) :
I believe that you meant that while the methods already exist, you just want to
call the methods by generated name -- right? Your example bears this out:
> while (my $hrRes = $sth->fetchrow_hashref)
> {
> foreach (@fields)
> {
> $self->"set".$_($hrRes->{$_});
> # resulting in e.g. $self->setDate($hrRes->{'Date'}) or
> # $self->setAmount($hrRes->{'Amount'})
> }
> }
You can call methods by generated name, but you must put the name in a scalar
first. You can't say:
my $value = $object->"method" . "_etc";
You can say:
my $method_name = "method" . "_etc";
my $value = $object->$method_name;
Does that clear this up?
--
rjbs
|
|
|
|
|