String Eval

From Erlang Community

(Difference between revisions)
Revision as of 21:55, 3 September 2006 (edit)
Bfulgham (Talk | contribs)

← Previous diff
Revision as of 10:44, 25 September 2006 (edit) (undo)
Ayrnieu (Talk | contribs)
(clean up the example.)
Next diff →
Line 5: Line 5:
== Solution == == 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: +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:
<code> <code>
-1> {ok,A,B} = erl_scan:string("A = 1 + 2.").+eval(S,Environ) ->
-{ok,[{var,1,'A'},{'=',1},{integer,1,1},{'+',1},{integer,1,2},{dot,1}],1}+ {ok,Scanned,_} = erl_scan:string(S),
-2> A.+ {ok,Parsed} = erl_parse:parse_exprs(Scanned),
-[{var,1,'A'},{'=',1},{integer,1,1},{'+',1},{integer,1,2},{dot,1}]+ erl_eval:exprs(Parsed,Environ).
-3> {C,D} = erl_parse:parse_exprs(A).+ 
-{ok,[{match,1,{var,1,'A'},{op,1,'+',{integer,1,1},{integer,1,2}}}]}+1> eval("A = 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}]} {value,3,[{'A',3}]}
</code> </code>

Revision as of 10:44, 25 September 2006

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.

Erlang/OTP Projects
Personal tools