Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

erlang

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

like image 914
misiek Avatar asked Dec 13 '11 23:12

misiek


3 Answers

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.

like image 65
Cody Avatar answered Sep 30 '22 16:09

Cody


Youcan use the -eval switch instead.

erl -eval 'io:format("~p",[hello]).'
like image 30
Lukas Avatar answered Sep 30 '22 14:09

Lukas


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)).
like image 45
Ben Avatar answered Sep 30 '22 14:09

Ben