Call different functions depending on input

Hello! I’m writing some code including call different functions depend on whether the input string match certain pattern. Currently I’m writing code like this:

struct MyOperation
    fun::Symbol
    re::Regex
end

const operations = Vector{MyOperation}(some long list...)

function do_work(str::String)
    for op in operations
        if match(op.re ,str) !== nothing
            fun = eval(op.fun)
            fun(str)
        end
    end
end

But involving eval is clearly not good for performance. Is there a better way to do this? Thanks for any help.

You can just assign the function directly:

struct MyOperation
  fun::Function
  re::Regex
end

const operations = Vector{MyOperation}(some long list...)

function do_work(str::String)
    for op in operations
        if match(op.re ,str) !== nothing
            op.fun(str)
        end
    end
end

Oh… You are so right.

1 Like

Depending on the application, it may be too restrictive to require fun to be of type Function. One can apply other objects to strings, too. A built-in example is

julia> Symbol("xyz")
:xyz
1 Like