在Erlang ETS存储列表
问题描述:
我试图插入一个列表到ETS以后拔出,并由于某种原因它说这是一个坏的参数。我不确定是否我错误地插入了它。在Erlang ETS存储列表
难道仅仅是不可能向ETS插入一个列表?
违规行是ets:insert(table, [{parsed_file, UUIDs}])
。
下面是代码:
readUUID(Id, Props) ->
fun() ->
%%TableBool = proplists:get_value(table_bool, Props, <<"">>),
[{_, Parsed}] = ets:lookup(table, parsed_bool),
case Parsed of
true ->
{uuids, UUIDs} = ets:lookup(table, parsed_bool),
Index = random:uniform(length(UUIDs)),
list_to_binary(lists:nth(Index, UUIDs));
false ->
[{_, Dir}] = ets:lookup(table, config_dir),
File = proplists:get_value(uuid_file, Props, <<"">>),
UUIDs = parse_file(filename:join([Dir, "config", File])),
ets:insert(table, [{parsed_file, {uuids, UUIDs}}]),
ets:insert(table, [{parsed_bool, true}]),
Index = random:uniform(length(UUIDs)),
list_to_binary(lists:nth(Index, UUIDs))
end
end.
parse_file(File) ->
{ok, Data} = file:read_file(File),
parse(Data, []).
parse([], Done) ->
lists:reverse(Done);
parse(Data, Done) ->
{Line, Rest} = case re:split(Data, "\n", [{return, list}, {parts, 2}]) of
[L,R] -> {L,R};
[L] -> {L,[]}
end,
parse(Rest, [Line|Done]).
答
如果您在同一个进程内的表像
ets:new(table, [set, named_table, public]).
,那么你应该没问题。默认权限受到保护,只有创建过程才能写入。
答
为贯彻到我关于ETS表只含元组,什么ets:lookup/2
返回在下面的一行代码注释:
{uuids, UUIDs} = ets:lookup(table, parsed_bool),
将永远产生一个错误作为ets:lookup/2
返回一个列表。上面的3行代码可能会成功。看起来你正在试图在table
中使用键parsed_bool
进行2次查找,期望得到2种不同类型的答案:{_, Parsed}
和{uuids, UUIDs}
。请记住,ETS不提供键值表,而是其中一个元素(默认第一个元素)是键的元组表,它会返回包含该键的元组列表。你可以找回多少取决于表格的属性。
查看ETS tables的文档。
它适用于我...你确定那个调用insert的过程是ets或table的所有者是公共的吗?我没有看到负责创建它的代码。 [检查此](http://www.erlang.org/doc/man/ets.html)。 – 2014-12-19 04:16:58
您应该意识到只能将元组实际放入ETS表中,而不是列表。所以当你做'ets:insert(table,[...])''时,你实际上是将元组插入到列表中,而不是**它自己的列表。而当你做'ets:lookup(table,Key)'时,你会得到一个包含该键的元组列表。 – rvirding 2014-12-21 16:22:43