Erlang conversion for one format to another format

2019-08-05 00:54发布

问题:

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>


标签: erlang