Erlang 脚本参数
我真的不明白命令行参数如何与脚本一起使用。从联机帮助页中,我了解到参数作为字符串列表传递给 main/1。如何解析传递给 main 的参数?
考虑以下事项:
#!/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]).
一个简单的测试,只要一个参数,一切看起来都很好。
./test_server.erl 17001
Starting test server on port #17001
如果我传入多个参数怎么办?
./test_server.erl 17001 8 9 abc
Starting test server on port #1700189abc
那不是我想要的。我尝试在空格字符上拆分字符串:
....
ArgsList = string:tokens(Args, " "),
io:format("Length: ~w~n",[length(ArgsList)]),
....
Yields 长度:1
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
长度(L)
length/1
是一个内置函数,您可以按原样使用:Args
Args
是字符串列表。此调用(使用~p
作为格式):将产生结果:
如果您使用
~s
,Erlang 将其解释为字符串(或 IO 列表,实际上)并且打印出所有连接的元素。要一一打印出所有参数,请尝试使用以下方法代替 io:format/2 调用:
length(L)
length/1
is a built in function that you can use just as is:Args
Args
is a list of strings. This call (using~p
as format):Would yield the result:
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: