Possible Duplicate:
How do I implement dispatch tables in Perl?
I have a hash table that contains commands such as int(rand()) etc. How do I execute those commands?
Possible Duplicate:
How do I implement dispatch tables in Perl?
I have a hash table that contains commands such as int(rand()) etc. How do I execute those commands?
You can use eval($str)
to execute Perl code you store in a string variable, $str
. You could alternatively store your code as function references within a hash, so something like:
$hash{'random'} = sub { int(rand()) };
This way, you could write $hash{'random'}->()
to execute the function whenever you want a random value.
See also Implementing Dispatch Tables on PerlMonks.
As other have said, you can execute them using eval
. However, please note that executing arbitrary strings of possibly tainted origin via eval
is a major security hole, as well as prone to be slow if performance of your application matters.
You can use the Safe module to remove the security hole (not sure how bulletproof that is but much better than naked eval
), but performance issues will always be there as Perl will have to compile your code prior to executing it WHILE executing the main program.