e r l a n g : c o o k b o o k

/ Erlang.StringEval

This Web


WebHome 
WebChanges 
TOC
NewRecipe 
WebTopicList 
WebStatistics 

All Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Erlang Links


Erlang.org
Erlang Wiki
ErlMan
Erlang Wiki
The Jungerl
Erlang-fr.org
Joe Armstrong
Lambda the Ultimate

Erlang Web Ring


[Prev]: Joe Armstrong's Page
[Next]: Joe Armstrong's Page

Evaluating Erlang Code in a String

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.

Discussion

(String input ports and read)

See Also

StringInterpolation

-- NoelWelsh - 28 Apr 2004

-- BrentAFulgham - 21 Aug 2004

CookbookForm
TopicType: Recipe
ParentTopic: StringRecipes
TopicOrder: 110

 
 
Copyright © 2004 by the contributing authors. All material on the Erlang Cookbook web site is the property of the contributing authors.
This material can be redistributed and/or modified under the terms of the GNU Lesser General Public License (LGPL), version 2.1, as published by the Free Software Foundation.
Ideas, requests, problems regarding Schematics Cookbook? Send feedback.
/ You are Main.guest