Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper escript for Hello World in erlang?

Tags:

erlang

So I know that the basic Hello World Program (as in the one to output a string not the one designed for Erlang learning with spawn and other stuff) is as follows

-module(hello).
-export([start/0]).

start() ->
  io:format("Hello, World!").

Then I run erl

>erl

type

>c(hello)

and then

>hello

For the escript version would it be this ?

#!/usr/bin/env escript
-export([main/1]).

main([]) -> io:format("Hello, World!~n").

Then

chmod u+x hello

Where hello is the filename ?

Why can I not use the same format as the module ? (main/0 and main()) ?

like image 870
phwd Avatar asked Nov 18 '10 21:11

phwd


1 Answers

That is just the way the escript system works. Your escript must contain a function main/1 for the runtime to call. The escript needs a way to pass command line arguments to your function, and it does this as a list of strings, hence the need for your main function to take one argument.

When you build a module and run it manually from the shell, a similar requirement applies - your module must export the function you want to call (start/0 in your example).

In fact, your example is incorrect. You create and compile the module but never call it. Evaluating

 hello.

In the shell simply repeats the atom value hello. To actually call your hello world function you would need to evaluate:

hello:start().
like image 162
archaelus Avatar answered Nov 01 '22 02:11

archaelus