将一种格式的Erlang转换为另一种格式 [英] Erlang conversion for one format to another format

查看:102
本文介绍了将一种格式的Erlang转换为另一种格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Erlang中将字符串格式"{hari,localost}" 转换为 {"hari","localost"} ?

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.

推荐答案

我想您需要从字符串转换,因此可以使用模块erl_scan和erl_parse:

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>

注1 ,仅当Terms是有效的表达式时,函数erl_parse:parse_term/1才起作用,这就是为什么我必须添加"的原因.在输入的末尾.

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.

注释2 如果您在输入表达式中引用术语,则可以直接转换为最终表达式:

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转换为另一种格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆