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
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].
精彩评论