That’s what it takes to write an Hello World program in Erlang, after you installed the Erlang system on your machine.
Here’s the program itself:
<span><span class="S6">-</span><span class="S4">module</span><span class="S6">(</span><span class="S7">hello</span><span class="S6">).</span><br />
<span class="S6">-</span><span class="S4">export</span><span class="S6">([</span><span class="S8">hello_world/0</span><span class="S6">]).</span><br />
<br />
<span class="S7">hello_world</span><span class="S6">()-></span><br />
<span class="S0"> </span><span class="S7">io</span><span class="S6">:</span><span class="S7">format</span><span class="S6">(</span><span class="S5">"Hello World ~n"</span><span class="S6">).</span><span class="S0"> </span></span>
What does that means? Briefly:
- -module(hello).
- Create a module for the following functions, think of it like a namespace declaration.
- -export([hello_world/0]).
- This tells the compiler that we want to export the
function to the outer world. It means the other modules can call this function. What does the “/0″ means? It means the “hello_world” function with 0 parameters. In Erlang, you can have different functions with the same name and different number of parameters.
- hello_world()->
- Declare a new function named “hello_world” that accept no parameters, the body will follow the arrow.
- io:format(“Hello World ~n”).
- This calls the “format” function from the module “io” that prints out the Hello World message. The “~n” characters prints the Carriage Return, the same as “/n” in other languages.
To run your program you must start the Erlang shell first:
$ erl
Erlang (BEAM) emulator version 5.5.4 [async-threads:0]
Eshell V5.5.4 (abort with ^G)
1> c(hello).
{ok,hello}
2> hello:hello_world().
Hello World
ok
3>
Try it, and understand it. Next time will be a little bit more complex!
Note: if you guess why by copying and pasting the code you get a lot of errors, that’s because SciTe, the editor I use, exports the code with fancy double quotes. That’s a good reason to not being lazy and write the program by yourself! Writing it’s a nice way of learning!