Slides for brief talk about writing CLI applications with Elixir with sample application
How do you parse command line arguments?
The main function has the command line arguments as a list of Strings as it's input. The most straightforward way to parse them is to use the OptionParser module that is part of the standard elixir libraries.
def main(args) do
args |> parse_args |> process |> cleanup
end
def parse_args(args) do
# Default options
options = %{ :greeting => "Hello" ,
:audience => "World" }
cmd_opts = OptionParser.parse(args,
switches: [help: :boolean , greeting: :string, audience: :string],
aliases: [h: :help, g: :greeting, a: :audience])
case cmd_opts do
{ [ help: true], _, _} -> :help
{ [], args, [] } -> { options, args }
{ opts, args, [] } -> { Enum.into(opts,options), args }
_ -> :help
end
end
Keeping the parsed options and args in a { Map, List } tuple that is used as the first arg of your processing functions works out well.