仅从 erlang 中的 ref 中提取数字

Extract only the number from a ref in erlang

我是 Erlang 的新手。 我只需要取 make_ref() 返回的数字。 所以,如果 make_ref() returns :#Ref<0.0.0.441> 我想从中提取 441。

知道怎么做吗?

试试这个:

unique_integer() ->
    try
        erlang:unique_integer()
    catch
        error:undef ->
            {MS, S, US} = erlang:now(),
            (MS*1000000+S)*1000000+US
    end.

编辑: 此解决方案与使用 io_lib:format("~p", [Ref]) 提取整数的主要区别在于速度。当我的解决方案在 R18 中花费大约 40ns 时,转换为列表、正则表达式并返回整数需要 9µs。我会寻求两个数量级更快的解决方案。

erlang:ref_to_list/1 函数可将引用转换为列表,但文档警告不要在生产代码中使用它。我们可以使用 io_lib:format/2 代替。将 ref 转换为列表后,我们可以使用正则表达式提取数字。

这是一个从 ref 的字符串表示中提取数字的函数:

extract_from_ref(Ref) when is_reference(Ref) ->
    [RefString] = io_lib:format("~p", [Ref]),
    {match, L} = re:run(RefString,
                        "#Ref<(\d+)\.(\d+)\.(\d+)\.(\d+)>",
                        [{capture, all_but_first, list}]),
    IntList = lists:map(fun list_to_integer/1, L),
    list_to_tuple(IntList).

要仅获取 ref 的字符串表示形式的最后一个数字,您可以这样使用它:

{_, _, _, N} = extract_ref(make_ref()).