【发布时间】:2015-12-26 12:48:22
【问题描述】:
{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
我在读取 /etc/hosts 文件并尝试使用 String.split 逐行拆分它时具有以下长生不老药功能。
然后我映射主机的行列表并为每个主机调用 line_to_host(host)。 line_to_host 方法将行分割为" ",然后我想设置from 和to 变量:
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 文档并在 Google 上搜索了如何在特定索引处获取列表元素。
我知道有head/tail,但必须有更好的方法来获取列表元素。
elem(list, index) 完全符合我的需要,但不幸的是它不适用于 String.split。
如何在 elixir 中通过 ID 获取列表/元组元素
【问题讨论】:
-
你不想在
{status, body} = File.read("/etc/hosts")后面跟着if。首选模式匹配:case File.read("/etc/hosts") do {:ok, body} -> ... -
好的,很高兴知道这一点。谢谢朋友。