Command Line Arguments in Erlang
Command-line arguments are a common way to parameterize execution of programs. For example, erl -noshell -s hello_world main -s init stop uses -noshell, -s, hello_world, main, -s, init, and stop as arguments to the erl program.
-module(command_line_arguments).
-export([main/1]).
main(Args) ->
% The first argument is the script name, which we can ignore
ArgsWithoutProg = tl(Args),
% You can get individual args with normal list operations
Arg = lists:nth(3, Args),
io:format("~p~n", [Args]),
io:format("~p~n", [ArgsWithoutProg]),
io:format("~p~n", [Arg]).In Erlang, the command-line arguments are passed to the main/1 function as a list of strings. The first element of this list is typically the name of the script being run.
To experiment with command-line arguments, it’s best to compile the module first and then run it using the erl command.
$ erlc command_line_arguments.erl
$ erl -noshell -s command_line_arguments main a b c d -s init stop
["command_line_arguments","a","b","c","d"]
["a","b","c","d"]
"c"In this example, we compile the Erlang module using erlc, then run it using erl. The -noshell option prevents the Erlang shell from starting, -s command_line_arguments main calls the main/1 function in our module, a b c d are the arguments we’re passing to our program, and -s init stop tells Erlang to exit after running our program.
Erlang doesn’t have a direct equivalent to Go’s os.Args, but instead passes the command-line arguments directly to the main/1 function. The tl/1 function is used to get all elements of the list except the first one, which is equivalent to os.Args[1:] in Go.
Next, we’ll look at more advanced command-line processing with option parsing libraries in Erlang.