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?

Community
  • 1
  • 1
Chaggster
  • 2,441
  • 3
  • 21
  • 14
  • Duplicate: "How do I implement dispatch tables in Perl?" http://stackoverflow.com/questions/1281456/how-do-i-implement-dispatch-tables-in-perl – Sinan Ünür Dec 15 '09 at 14:01
  • 2
    Hashes hold scalar values. It could be helpful for providing relevant examples in answers if you described (with code) how you stored "commands" in the hash in the first place. Perl code in a string? Subroutine reference? Something else? – Rob Kennedy Dec 15 '09 at 14:43

2 Answers2

5

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.

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
JBD
  • 204
  • 2
  • 4
  • 1
    `eval` is almost never the best way to do it (where "it" == pretty much anything). Anonymous subrefs would be much better. – Ether Dec 15 '09 at 18:52
  • **String eval** is almost never the best way to do it. Block eval is another story. – daotoad Dec 15 '09 at 19:36
1

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
  • 126,886
  • 32
  • 213
  • 327
  • 1
    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 Dec 15 '09 at 14:38