boaz
boaz

Reputation: 900

Extract only the number from a ref in erlang

I'm new to Erlang. I need to take only the number returned from make_ref(). so, if make_ref() returns :#Ref<0.0.0.441> I would like to extract from it the 441.

any idea how to do this?

Upvotes: 1

Views: 332

Answers (2)

Hynek -Pichi- Vychodil
Hynek -Pichi- Vychodil

Reputation: 26121

Try this instead:

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

Edit: The main difference between this solution and extracting integer using io_lib:format("~p", [Ref]) is speed. When my solution takes around 40ns in R18, transformation to a list, regexp and back to an integer takes 9µs. I would go for two orders of magnitude faster solution.

Upvotes: 3

TKLX
TKLX

Reputation: 21

There is the erlang:ref_to_list/1 function to convert a ref to a list, but the documentation warns against using it in production code. We can use io_lib:format/2 instead. After converting the ref to a list, we can extract the numbers using a regexp.

Here's a function for extracting numbers from the string representation of a 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).

To get only the last number of the string representation of a ref, you can use it like this:

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

Upvotes: 0

Related Questions