使用erlang实现动态替换字符串中的变量

通过erlang,我们可以使用
{ok, Ts, _} = erl_scan:string(String).
来获取Tokens,然后调用:
{ok, Expr} = erl_parse:parse_exprs(Ts).
转换成可以执行的表达式,之后通过
erl_eval:exprs(Expr, Binding).
来执行表达式。
实验步骤如下:
1> F =fun(Str,Binding) ->
1>      {ok,Ts,_} = erl_scan:string(Str),
1>      io:format("~p~n", [Ts]),
1>      Ts1 = case lists:reverse(Ts) of
1>               [{dot,_}|_] -> Ts;
1>               TsR -> lists:reverse([{dot,1} | TsR])
1>           end,
1>      io:format("~p~n", [Ts1]),
1>     {ok,Expr} = erl_parse:parse_exprs(Ts1),
1>     io:format("~p~n", [Expr]),
1>     erl_eval:exprs(Expr, Binding) end.
#Fun<erl_eval.12.113037538>
2> F("lists:concat(['haha',B,'ok!']).",[{'B',23}]).
[{atom,1,lists},
 {':',1},
 {atom,1,concat},
 {'(',1},
 {'[',1},
 {atom,1,haha},
 {',',1},
 {var,1,'B'},
 {',',1},
 {atom,1,'ok!'},
 {']',1},
 {')',1},
 {dot,1}]
[{atom,1,lists},
 {':',1},
 {atom,1,concat},
 {'(',1},
 {'[',1},
 {atom,1,haha},
 {',',1},
 {var,1,'B'},
 {',',1},
 {atom,1,'ok!'},
 {']',1},
 {')',1},
 {dot,1}]
[{call,1,
       {remote,1,{atom,1,lists},{atom,1,concat}},
       [{cons,1,
              {atom,1,haha},
              {cons,1,{var,1,'B'},{cons,1,{atom,1,'ok!'},{nil,1}}}}]}]
{value,"haha23ok!",[{'B',23}]}
3> 

你可能感兴趣的:(erlang,erl_scan,erl_eval,erl_parse)