Erlang 脚本参数

发布于 2024-10-17 19:56:34 字数 770 浏览 2 评论 0原文

我真的不明白命令行参数如何与脚本一起使用。从联机帮助页中,我了解到参数作为字符串列表传递给 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

家住魔仙堡 2024-10-24 19:56:34

长度(L)

length/1 是一个内置函数,您可以按原样使用:

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

Args

Args 是字符串列表。此调用(使用 ~p 作为格式):

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

将产生结果:

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

如果您使用 ~s,Erlang 将其解释为字符串(或 IO 列表,实际上)并且打印出所有连接的元素。

要一一打印出所有参数,请尝试使用以下方法代替 io:format/2 调用:

[io:format("~s~n", [A]) || A <- Args].

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].
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文