Search code examples
elixir

Transform Process ID (`pid`) in Elixir to Tuple or string; Parse `pid` to other types


How do I transform a Process ID PID into a tuple or string?

For example, let's say I have a PID named my_pid

iex(1)> my_pid
#PID<0.1692.0>

How would I transform the PID ID to a tuple or a string to get either?

{ 0, 1692, 0 }

or

"0.1692.0"

Solution

  • You are after :erlang.pid_to_list/1 and :erlang.list_to_pid/1 functions.

    list = self() |> :erlang.pid_to_list()
    #⇒ [60, 48, 46, 49, 49, 48, 46, 48, 62]
    to_string(list)
    #⇒ "<0.110.0>"
    list |> List.delete_at(0) |> List.delete_at(-1) |> to_string()
    #⇒ "0.110.0"
    

    The advantage of this approach is that it’s convertible

    :erlang.list_to_pid(list)
    #⇒ #PID<0.110.0>