Search code examples
erlangelixirelixir-mix

Elixir - Mix run example with arguments


Elixir is powered by Erlang OTP, which uses Mix as a build tool for creating and running applications.

I am now learning elixir as a beginner

I can create a mix application from command line by specifying mix new sample and I write some code in this to learn the basics of elixir and mix.

exs and ex file could be run by using the command mix run sample.exs

I am trying to write a code to get a specific type of number ,say prime numbers between a particular range (100000,20000)

I want to give the two numbers (100000,200000) as arguments to the mix run command like mix run sample.exs 100000,200000 and get the result in the given range.

Note - I dont want to build and executable using escript and need to use only the mix run command and also not mix run -e

How to get the args as input values in the exs file ?

Thanks a lot


Solution

  • While System.argv/0 somewhat works in trivial cases, we usually use OptionParser for more or less sophisticated options processing.

    ["--start", "0", "--end", "42"]
    |> OptionParser.parse(
      strict: [start: :integer, end: :integer]
    )
    |> IO.inspect()
    #⇒ {[start: 0, end: 42], [], []}
    

    To use these values:

    {args, _, _} =
      OptionParser.parse(
        ["--start", "0", "--end", "42"],
        strict: [start: :integer, end: :integer]
      )
    Enum.each(args[:start]..args[:end], &IO.inspect/1)