【问题标题】:Elixir command line app with list as parameter以列表为参数的 Elixir 命令行应用程序
【发布时间】:2016-12-12 21:00:56
【问题描述】:

我正在使用以下代码作为我的解析函数使用 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

我的问题是如何将逗号分隔的字符串(二进制)转换为列表或任何更好的方法来做到这一点。

【问题讨论】:

    标签: list elixir


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2015-03-04
      • 1970-01-01
      • 1970-01-01
      • 2013-11-26
      • 2019-07-20
      • 1970-01-01
      • 2013-10-26
      • 2021-04-08
      • 2011-11-07
      相关资源
      最近更新 更多