5

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...

3 Answers 3

5

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.

1
  • Note that for command line usage you don't have to call it start you could also define it as sum like so: sum([X, Y]) -> sum(X, Y). and export as sum/1 (you then don't necessarily need to export the sum/2 version). Wasn't immediately obvious to me as a newbie to Erlang.
    – atomicules
    Commented Dec 3, 2013 at 15:00
4

Youcan use the -eval switch instead.

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

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)).
3
  • I knew there had to be a more elegant way to pick the integers out of the list. Thanks! :)
    – Cody
    Commented Dec 14, 2011 at 3:32
  • This is not a very general case though. Commented Dec 14, 2011 at 10:11
  • Indeed it's not, as it assumes a list of two elements for a parameter. It does match the original question, and the generalization of this approach is straightforward. What would you suggest?
    – Ben
    Commented Dec 14, 2011 at 19:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.