DogEatDog
DogEatDog

Reputation: 3047

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"

Upvotes: 2

Views: 2446

Answers (3)

Iftakhar Husan
Iftakhar Husan

Reputation: 51

Another useful approach to getting pid from a string representation of pid(eg. #PID<0.127.0>) is below, it's a derived version of Aleksei's solution.

Below is the snippet from iex session:

iex(1)> pid = "#PID<0.127.0>" |> String.trim_leading("#PID") |> String.to_charlist |> :erlang.list_to_pid  
#PID<0.127.0>
iex(2)> Process.alive?(pid)
true

Upvotes: 1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

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>

Upvotes: 12

GavinBrelstaff
GavinBrelstaff

Reputation: 3069

step by step:

pid = self()         # gets shells pid e.g. #PID<0.105.0>

a = "#{inspect pid}" # gives the string "#PID<0.105.0>"

b = String.slice a, 5,100 # remove the prefix #PID<
c = String.trim b, ">"    # remove the postfix >
d = String.split c, "."   # create list of strings: ["0", "105", "0"]

e = Enum.map( d ,fn x -> String.to_integer(x) end) # converts to a list of integers
f = Enum.join(e, " ")

result: "0 105 0"

Upvotes: 6

Related Questions