[英]Extract only the number from a ref in erlang
我是Erlang的新手。 我只需要接受從make_ref()返回的數字。 因此,如果make_ref()返回:#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
函數將ref轉換為列表,但是文檔警告不要在生產代碼中使用它。 我們可以改用io_lib:format/2
。 將引用轉換為列表后,我們可以使用正則表達式提取數字。
這是一個從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).
要僅獲取引用的字符串表示形式的最后一個數字,可以像這樣使用它:
{_, _, _, N} = extract_ref(make_ref()).
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.