Erlang Central

String Eval

Revision as of 00:18, 26 September 2006 by Ayrnieu (Talk | contribs)

Problem

You want to evaluate Erlang code stored in a string.

Solution

Use erl_scan:string/1 to convert the string into a list of tokens, then use erl_parse:parse_exprs/1 to generate the Erlang intermediate representation, then finally use erl_eval:exprs/2 to generate the final output:

eval(S,Environ) ->
    {ok,Scanned,_} = erl_scan:string(S),
    {ok,Parsed} = erl_parse:parse_exprs(Scanned),
    erl_eval:exprs(Parsed,Environ).

1> eval("A = 1 + 2.",[]).
{value,3,[{'A',3}]}

Now, this is an admittedly baroque way to determine the value of 1 + 2, but it does give you interesting access to the inner workings of the Erlang interpreter.