Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang escript arguments

I don't really understand how command line arguments work with escripts. From the manpage, I understand that the arguments are passed as a list of strings to main/1. How can I parse the arguments passed to main?

Consider the following:

#!/usr/bin/env escript
usage() ->
  io:format("Usage: ~s <port#>~n",[escript:script_name()]),
  halt(1).

main([]) ->
  usage();
main(Args)->
  io:format("Starting test server on port #~s~n",[Args]).

A simple test and all looks good with just one argument.

  ./test_server.erl 17001
   Starting test server on port #17001

What about if I pass in multiple arguments?

  ./test_server.erl 17001 8 9 abc
   Starting test server on port #1700189abc

That is not what I wanted. I tried spliiting the string on the space character:

  ....
  ArgsList = string:tokens(Args, " "),
  io:format("Length: ~w~n",[length(ArgsList)]),
  ....

Yields Length: 1

like image 706
Dr. Watson Avatar asked May 09 '26 08:05

Dr. Watson


1 Answers

length(L)

length/1 is a built in function that you can use just as is:

io:format("Length: ~p~n", [length(Args)])

Args

Args is a list of strings. This call (using ~p as format):

io:format("Starting test server on port #~p~n", [Args]).

Would yield the result:

./test_server.erl 17001 8 9 abc
Starting test server on port #["17001","8","9","abc"]

If you're using ~s, Erlang interprets it as a string (or IO list, really) and that gets printed with all the element concatenated.

To print out all arguments one by one, try this instead of the io:format/2 call:

[io:format("~s~n", [A]) || A <- Args].
like image 195
Adam Lindberg Avatar answered May 11 '26 15:05

Adam Lindberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!