简体   繁体   中英

how to run an erlang program with function of arity larger than 1 from a command line

How to run a function of arity larger than 1 from UNIX command line?

example program:

-module(test).
-export([sum/2]).
sum(X,Y)->io:write(X+Y).

After compiling

erlc test.erl

I'm trying something like

erl -noshell -s test sum 5 3 -s init stop

but obviously it doesn't work because it treats 5 3 as list...

Create a function that takes a list, like so:

-module(test).
-export([sum/2, start/1]).

start(Args) ->
  % Pick X and Y args out of Args list and convert to integers
  sum(X, Y).
sum(X, Y) -> io:write(X+Y).

Now when your command line passes the list to the start function, it'll break the list down and do the summation. Note I haven't tested this, but it should work if you are getting the arguments as a list.

您可以使用-eval开关。

erl -eval 'io:format("~p",[hello]).'

I'm not aware of any way to get around the requirement that the named function take one argument. As Cody mentions, that one argument can be a list, which you can destructure in the parameter list definition.

Using the command line you gave, this works for me:

-module(test).
-export([sum/1]).

sum([X, Y]) ->
    io:format("X: ~p Y: ~p", [X, Y]),
    list_to_integer(atom_to_list(X)) + list_to_integer(atom_to_list(Y)).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM