Erlang conversion for one format to another format

↘锁芯ラ 提交于 2019-12-11 06:13:17

问题


How to convert this string format "{hari, localost}" into this: {"hari", "localost"}, in Erlang?

I tried to convert this format with lot of trial and error method, but I can't get the solution.


回答1:


I guess you need to convert from string, so you can use the modules erl_scan and erl_parse:

1> erl_scan:string("{hari, localost}"++".").
{ok,[{'{',1},
     {atom,1,hari},
     {',',1},
     {atom,1,localost},
     {'}',1},
     {dot,1}],
    1}
2> {ok,Term} = erl_parse:parse_term(Tokens).             
{ok,{hari,localost}}
3>Conv = fun({X, Y}) -> {atom_to_list(X), atom_to_list(Y)} end.
#Fun<erl_eval.6.80484245>
4> Conv(Term).
{"hari","localost"}
5>

Note 1 the function erl_parse:parse_term/1 will work only if Terms is a valid expression, it is why I had to add a "." at the end of the input.

Note 2 yo can directly transform to the final expression if you quote the terms in the input expression:

1> {ok,Tokens,_} = erl_scan:string("{\"hari\", \"localost\"}.").     
{ok,[{'{',1},
     {string,1,"hari"},
     {',',1},
     {string,1,"localost"},
     {'}',1},
     {dot,1}],
    1}
2> {ok,Term} = erl_parse:parse_term(Tokens).                        
{ok,{"hari","localost"}}
3>


来源:https://stackoverflow.com/questions/21551635/erlang-conversion-for-one-format-to-another-format

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!