Re: How to dynamically generate function name and call it?



Hemant Shah <shah@xxxxxxxxxxxxxxxx> wrote
How do I dynamically generate function and then execute the function?

Two ideas: Either try utilising a hash as a lookup table:

Example:

if ($TableName eq "TRAC")
{
CreateTRACTable();
}
elsif ($TableName eq "TRCO")
{
CreateTRCOTable();
}

my %table_actions = (
TRAC => \&CreateTRACTable,
TRCO => \&CreateTRCOTable,
);

$table_actions{$TableName}->(@arguments);

which would mean you still have to define all actions. If this is
good or bad depends on your situation. If there's really no problem
or danger for you (e.g. nothing user supplied or invalidated, etc.)
then there's the symbolic reference way:

{ no strict 'refs'; # turn this off in smallest scope
*{'Create' . $TableName . 'Table'}->(@arguments);
}

This assumes that you're using strict and warnings, which you should
always have turned on.

Depending on your design you might also want to think about some
approach that doesn't need this (the second solution, that is). This can
lead to applications that are harder to maintain in my experience. But
it's imho really great for smaller software projects or prototyping.

hth,
phaylon

--
thou shallst fear ..

.