{status, body} = File.read("/etc/hosts")
if status == :ok do
hosts = String.split body, "\n"
hosts = Enum.map(hosts, fn(host) -> line_to_host(host) end)
else
IO.puts "error reading: /etc/hosts"
end
I have the following elixir function where I read the /etc/hosts file and try to split it line by line using String.split
.
Then I map through the line list of hosts and call line_to_host(host) for each. The line_to_host method splits the line by " "
and then I want to set the from
and to
variable:
def line_to_host(line) do
data = String.split line, " "
from = elem(data, 0) // doesn't work
to = elem(data, 1) // doesn't work either
%Host{from: from, to: to}
end
I looked through stackoverflow, the elixir docs and googled about how to get an list element at a specific index.
I know there is head/tail
but there has to be a better way of getting list elements.
elem(list, index)
does exactly what I need but unfortunately it's not working with String.split
.
How to get list/tuple elements by ID in elixir
{status, body} = File.read("/etc/hosts")
followed byif
. Prefer pattern matching:case File.read("/etc/hosts") do {:ok, body} -> ...
– José Valim