繁体   English   中英

以列表为参数的Elixir命令行应用

[英]Elixir command line app with list as parameter

我正在使用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

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

您可以使用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"]

我将使用第一个,除非您的字符串可以包含逗号(在这种情况下,您可以使用另一个定界符)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM