Reputation: 740
i'm building a simple CLI app with elixir using the following code as my parse function
def parse_args(args) do
options = OptionParser.parse(args)
case options do
{[list: list], _, _} -> [list]
_ -> :help
end
end
calling the app with
./app --list one,two,three
my problem is how to convert comma separated string (binary) into list or any better way to do this.
Upvotes: 0
Views: 687
Reputation: 222118
You can either split using 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"]
or use the strict: [list: :keep]
option and pass the arguments as ./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"]
I would use the first one unless your strings can contain a comma (in that case you could use another delimiter).
Upvotes: 3