Erlang Central

Difference between revisions of "String Eval"

From ErlangCentral Wiki

 
Line 21: Line 21:
 
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.  
 
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.  
  
[[Category:CookBook]]
+
[[Category:CookBook]][[Category:StringRecipes]]

Revision as of 21:55, 3 September 2006

Problem

You want to evaluate Erlang code stored in a string.

Solution

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

1> {ok,A,B} = erl_scan:string("A = 1 + 2.").
{ok,[{var,1,'A'},{'=',1},{integer,1,1},{'+',1},{integer,1,2},{dot,1}],1}
2> A.
[{var,1,'A'},{'=',1},{integer,1,1},{'+',1},{integer,1,2},{dot,1}]
3> {C,D} = erl_parse:parse_exprs(A).
{ok,[{match,1,{var,1,'A'},{op,1,'+',{integer,1,1},{integer,1,2}}}]}
4> D.
[{match,1,{var,1,'A'},{op,1,'+',{integer,1,1},{integer,1,2}}}]
5> erl_eval:exprs(D,[]).
{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.