Hello, World!
The program
A complete program which prints “Hello, World!” is really easy:
-module(world).
-export([start/0]).
start() ->
io:format("Hello, World!").
That's it!
Let's look line-by-line what's going on here. First, you need to declare a module name:
-module(world).
Modules is a modern way of composing your code. Module is a single yet complete unit of code which provides some API. Module is something like a library. However real life library is something rather large, when a module is a unit of code of any size. It's OK when a module has just a couple of lines of code. In the example above we've named our module world
.
The next thing is a list of functions exported from the module. Exported functions are functions visible from the outside. It's module API. To use a module from the outside — is to use its exported functions. To export a function we should mention its name and parameters count within -export
directive:
-export([start/0]).
In the example above we export function start
which has no parameters.
If the function isn't exported then it is visible and can be used inside its module only. So, functions exporting (or not exporting) is a way of encapsulation.
And the last, our only function:
start() ->
io:format("Hello, World!").
It's kinda obvious: function name, parameters list (empty list in our case), an arrow, and a function body after that. io
is a built-in module for I/O operations, format
is io
module's function which prints a formatted string into stdout.
Build and run
Usually it is advised to learn how to use Erlang shell. How to compile and run Erlang programs there. But we won't do that! Not today, at least. I don't want to draw your attention away and bother with some tools, I want you to focus on the language instead. So we'll write a script to build and run your code and won't return to this for a while:
erlc world.erl
erl -noshell -s world start
Put this commands into .cmd
file if you're on Windows and into .sh
if you're on Linux or MacOS. The first command compiles your code into .beam
file while the second runs it without shell. Two last arguments are module name and function name which you want to run.
Also you should put Erlang installation path into %PATH%
environment variable either write full path to both erlc
and erl
tools in the build script. Both will work.
Note that module name should match its file name — it's required by the language.
So, now we can build and run our very first Erlang program:
> run.sh
> erlc world.erl
> erl -noshell -s world start
Hello, World!
Well, looks like everything works fine so far!