Erlang trying to evaluate a string

坚强是说给别人听的谎言 提交于 2019-12-12 02:48:37

问题


I'm trying to dynamically evalutate Erlang terms

Start up Erlang

basho-catah% erl
Erlang R16B03 (erts-5.10.4) [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]

Eshell V5.10.4  (abort with ^G)

Create a term

1> {a,[b,c,d]}.
{a,[b,c,d]}

Try to scan in the same term

2> {ok, Tokens, _ } = erl_scan:string("{a,[b,c,d]}").
{ok,[{'{',1},
     {atom,1,a},
     {',',1},
     {'[',1},
     {atom,1,b},
     {',',1},
     {atom,1,c},
     {',',1},
     {atom,1,d},
     {']',1},
     {'}',1}],
    1}


3> Tokens.
[{'{',1},
 {atom,1,a},
 {',',1},
 {'[',1},
 {atom,1,b},
 {',',1},
 {atom,1,c},
 {',',1},
 {atom,1,d},
 {']',1},
 {'}',1}]

But it can't parse that tokenized string.

4> Foo = erl_parse:parse(Tokens).
{error,{1,erl_parse,["syntax error before: ","'{'"]}}

Any ideas what I'm doing wrong?


回答1:


You're using the wrong function, and there's also a caveat you haven't encountered.

First, the function you should be using is erl_parse:parse_term/1. I'm not actually able to find documentation for erl_parse:parse/1, so I suspect it's deprecated (and most likely used for parsing abstract-syntax trees, not tokens).

Second, for erl_parse:parse_term/1 to work, you must include the terminating dot character in your term. erl_scan:string/1 will happily convert whatever you give it into tokens, but without the terminator erl_parse:parse_term/1 expects to receive more.

So, try the following in a shell:

{ok, Tokens, _} = erl_scan:string("{a,[b,c,d]}.").
erl_parse:parse_term(Tokens).


来源:https://stackoverflow.com/questions/23811143/erlang-trying-to-evaluate-a-string

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