2

以下允许将元组或对象转换回 erlang 中的对象:

{ok, Tokens, _} = erl_scan:string("{'abc',123}."),
{ok, X} = erl_parse:parse_term(Tokens).

但是当您将记录表示为字符串时,例如:

-record(myrecord,{firstname,lastname,age}).
...
RecString = "#myrecord{firstname='john',lastname='doe',age=22}.",
{ok, Tokens, _} = erl_scan:string(RecString),
{ok, X} = erl_parse:parse_term(Tokens).

...以上将失败并显示以下消息:

** 异常错误:右侧值不匹配 {error,{1,erl_parse,["syntax error before: ",[]]}}

关于如何实现这一目标的想法?谢谢。

4

1 回答 1

5

首先,您必须记住,记录不作为数据类型存在,内部记录是元组,其中第一个元素是记录的名称。因此,根据您的记录定义:

-record(myrecord,{firstname,lastname,age}).

创建记录

#myrecord{firstname='john',lastname='doe',age=22}

将导致元组

{myrecord,john,doe,22}

它只包含实际数据。这就是记录的定义方式,请参见此处

Second point is that records are purely compile-time syntactic constructions which compiler transforms in tuple operations. So the definition of a record does not exist as such as data anywhere. Only the compiler knows of record definitions. So when you print a record all you see is the tuple. However you can define record inside the shell so you can use record syntax in the shell, see in the shell documentation.

So in this sense you cannot really convert a record to/from its string representation. You can parse the string but this only returns the abstract syntax which is not what you are after. They are expressions so you need to end the string with a . and use erl_parse:exprs/1.

希望这可以帮助。你想做什么?或者更确切地说,你为什么要这样做?

于 2013-02-17T21:23:39.080 回答