Search code examples
functioncoding-styleeval

calling different functions based on a string


I am not sure if it's even possible. Say I have the following function defined:

a(), b(), c()

I want to get a user input from command line (either "a", "b", "c") and according to the input call the corresponding function

BUT without using cases or if's ie:

input = getinput()
if exist?(input){
  input()
}

Does this exist in any language?


Solution

  • Sure you can do something like that. For instance, in Python:

    def a():
        return 'a'
    
    def b():
        return 'b'
    
    def select_func(name):
        return eval(name)()
    

    Executing select_func('a') will return 'a', and executing select_func('c') will raise an exception