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?


By implementing a "dispatch table", usually a hash where the values
are all CODE references.


I have a perl script that is used to drop/create/update database tables.
The script has drop/create/update functions for each table, and I
have if statements to call appropriate functions:

Example:

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

and so on.


How do I do this?


my %actions = ( # a "dispatch table", untested
TRAC => \&CreateTRACTable,
TRCO => \&CreateTRCOTable
);

...

die "don't know what action to take for '$TableName'\n"
unless exists $actions{ $TableName };

$actions{ $TableName }->(); # call the appropriate function


--
Tad McClellan SGML consulting
tadmc@xxxxxxxxxxxxxx Perl programming
Fort Worth, Texas
.