0
votes

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

2
Sidenote: mix has nothing to do with OTP, it’s pure elixir.Aleksei Matiushkin
yes thats right ... just mentioned that elixir uses mix as a build toolSkadoosh
Please stop putting parallel-processing tag everywhere. The questions you ask have nothing to do with parallel processing. Also, do you really want answers in erlang? If not, do not put this tag as well.Aleksei Matiushkin

2 Answers

5
votes

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)
3
votes

In order to get the arguments that were passed to your program, you need to use System.argv(). For example, given the following exs script:

args = System.argv()  
       |> IO.inspect()

and running elixir so_exs.exs input_1 input_2 (note I don't have a Mix project here so I am not using mix run) you get the following. The args variable now contains a list of all the arguments passed to the program:

["input_1", "input_2"]