Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass command-line arguments to a Erlang program?

Tags:

erlang

I'm working on a Erlang. How can I pass command line parameters to it?

Program File-

-module(program).
-export([main/0]).

main() ->
    io:fwrite("Hello, world!\n").

Compilation Command:

erlc Program.erl

Execution Command-

erl -noshell -s program main -s init stop

I need to pass arguments through execution command and want to access them inside main written in program's main.

like image 976
Monti Chandra Avatar asked Aug 07 '15 07:08

Monti Chandra


People also ask

How do I pass a command line argument to a program?

If you want to pass command line arguments then you will have to define the main() function with two arguments. The first argument defines the number of command line arguments and the second argument is the list of command line arguments.

Is it possible to pass command line arguments to a test?

It is possible to pass custom command line arguments to the test module.


2 Answers

$ cat program.erl
-module(program).
-export([main/1]).

main(Args) ->
    io:format("Args: ~p\n", [Args]).
$ erlc program.erl 
$ erl -noshell -s program main foo bar -s init stop
Args: [foo,bar]
$ erl -noshell -run program main foo bar -s init stop
Args: ["foo","bar"]

It is documented in erl man page.

I would recommend using escript for this purpose because it has a simpler invocation.

like image 161
Hynek -Pichi- Vychodil Avatar answered Oct 19 '22 16:10

Hynek -Pichi- Vychodil


These are not really commandline-parameters, but if you want to use environment-variables, the os-module might help. os:getenv() gives you a list of all environment variables. os:getenv(Var) gives you the value of the variable as a string, or returns false if Var is not an environment-variable.

These env-variables should be set before you start the application.

I always use an idiom like this to start (on a bash-shell):

export PORT=8080 && erl -noshell -s program main
like image 26
Mathias Vonende Avatar answered Oct 19 '22 14:10

Mathias Vonende