Elixir命令行应用程序,列表作为参数

时间:2016-08-06 16:16:44

标签: list elixir

使用以下代码作为我的解析函数构建一个带有elixir的简单CLI应用程序

def parse_args(args) do
 options = OptionParser.parse(args)

 case options do
   {[list: list], _, _} -> [list]
   _ -> :help
 end
end

使用

调用应用
./app --list one,two,three

我的问题是如何将逗号分隔的字符串(二进制)转换为列表或更好的方法来执行此操作。

1 个答案:

答案 0 :(得分:3)

您可以使用String.split/2进行拆分:

iex(1)> {[list: list], _, _} = OptionParser.parse(["--list", "one,two,three"])
{[list: "one,two,three"], [], []}
iex(2)> String.split(list, ",")
["one", "two", "three"]

或使用strict: [list: :keep]选项并将参数传递为./app --list one --list two --list three

iex(1)> {parsed, _, _} = OptionParser.parse(["--list", "one", "--list", "two", "--list", "three"], strict: [list: :keep])
{[list: "one", list: "two", list: "three"], [], []}
iex(2)> Keyword.get_values(parsed, :list)
["one", "two", "three"]

我会使用第一个,除非你的字符串可以包含一个逗号(在这种情况下你可以使用另一个分隔符)。