Convert Keyword List into Map


I found a gentle and an in-depth article about OptionParser. Neither quite matched my specific use case of pattern matching options at the function level.

The key is converting the opts keyword list into a map.

defmodule Simple do
  def test(commandline) do
    {opts, _argv, _errors} = OptionParser.parse(commandline, switches: [pan_length: :integer])

    opts
    |> Enum.into(%{})
    |> doit()
  end

  def doit(%{pan_length: matches}) do
    IO.puts("PAN length is #{matches}")
  end

  def doit(%{}) do
    IO.puts("No PAN length given.")
  end
end

Simple.test(["--pan-length", "12"])
Simple.test([])
Simple.test(["--some-other-flag"])