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.
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.
It is possible to pass custom command line arguments to the test module.
$ 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With