{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
我有以下elixir函数,在其中读取/ etc / hosts文件并尝试使用逐行拆分String.split
。
然后,我通过主机的行列表进行映射,并为每个主机调用line_to_host(host)。line_to_host方法将行分割" "
,然后我要设置from
andto
变量:
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
我浏览了stackoverflow,elixir文档并用谷歌搜索了如何在特定索引处获取列表元素。我知道有,head/tail
但是必须有一种获取列表元素的更好方法。
elem(list, index)
完全满足我的需求,但不幸的是,它无法使用String.split
。
如何在Elixir中通过ID获取列表/元组元素
您可以为此使用模式匹配:
[from, to] = String.split line, " "
也许您想添加parts: 2
选项以确保在一行中有多个空格的情况下仅得到两部分:
[from, to] = String.split line, " ", parts: 2
也有Enum.at/2
,在这里可以正常使用,但是很简单。问题Enum.at
在于,由于Elixir中的列表实现,它需要遍历整个列表直到所请求的索引,因此对于大型列表而言效率可能非常低。
编辑:这是带有的请求的示例Enum.at
,但是在这种情况下我不会使用它
parts = String.split line, " "
from = Enum.at(parts, 0)
to = Enum.at(parts, 1)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句