{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
Just throw in |> IO. inspect(label: "foo") anywhere to print the value with a label without affecting the behavior of the original code.
The length() function returns the length of the list that is passed as a parameter.
Lists are a basic data type in Elixir for holding a collection of values. Lists are immutable, meaning they cannot be modified. Any operation that changes a list returns a new list. Lists implement the Enumerable protocol, which allows the use of Enum and Stream module functions.
It is essential to know that Elixir is immutable, so you cannot replace values in a list; actually, you create a new list. You can use the map method from Enum module, where you can found a bunch of algorithms to deal with enumerables.
You can use pattern matching for that:
[from, to] = String.split line, " "
Maybe you want to add parts: 2
option to ensure you will get only two parts in case there is more than one space in the line:
[from, to] = String.split line, " ", parts: 2
There is also Enum.at/3
, which would work fine here but is unidiomatic. The problem with Enum.at
is that due to the list implementation in Elixir, it needs to traverse the entire list up to the requested index so it can be very inefficient for large lists.
Edit: here's the requested example with Enum.at
, but I would not use it in this case
parts = String.split line, " " from = Enum.at(parts, 0) to = Enum.at(parts, 1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With