views:

123

answers:

2

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?

+5  A: 

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.

JBD
`eval` is almost never the best way to do it (where "it" == pretty much anything). Anonymous subrefs would be much better.
Ether
**String eval** is almost never the best way to do it. Block eval is another story.
daotoad
+1  A: 

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.

DVK
Please don't say *random* when you mean *arbitrary*, especially since the intended string would contain a call to `rand`, so it sounds like you're saying that that's somehow relevant, even though it's not. The security hole is that the string might come from an external source (like the user, or a text file).
Rob Kennedy
Good catch. Edited.
DVK