Erlang tries to evaluate a string
I am trying to dynamically evalutate Erlang members
Erlang launch
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 scanning in the same vein
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 cannot parse this tokenized string.
4> Foo = erl_parse:parse(Tokens).
{error,{1,erl_parse,["syntax error before: ","'{'"]}}
Any ideas what I am doing wrong?
source to share
You are using the wrong function, as well as a caveat you did not encounter.
First, the function you should be using is erl_parse:parse_term/1
. I can't find any documentation for erl_parse:parse/1
, so I suspect it's out of date (and most likely used to parse syntax trees, not tokens).
Second, to work, erl_parse:parse_term/1
you must include the line terminator in your term. erl_scan:string/1
will happily convert whatever you give to tokens, but without a terminator it erl_parse:parse_term/1
expects to get more.
So try this in a shell:
{ok, Tokens, _} = erl_scan:string("{a,[b,c,d]}.").
erl_parse:parse_term(Tokens).
source to share