Search code examples
erlangevaluationerlang-shell

Erlang trying to evaluate a string


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?


Solution

  • 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).