Go ahead and have a look the installation instructions for setting up Elixir. Once you’re done, come back to this page.
Dating back to the 1970s, the first program for learners trying out a new programming language has been to print the text Hello, world!
on screen.
Let’s try the same for Elixir. We’ll try out different ways to do it.
Go ahead and type the following code in an IDE / Text Editor of your choice.
IO.puts("Hello, world!")
Save the file as hello_world.exs
.
To run the program, type the following command in your terminal / command prompt:
elixir hello_world.exs
The file type .exs
indicates that it’s an Elixir script. You should see the following output printed on screen:
Hello, world!
Elixir can be both compiled and interpreted. Compiled code is faster than interpreted code, and it can be run on the BEAM VM, which is what we’ll be working with in the coming lessons.
For compiling the code, we’ll write it in .ex
files, which indicates to the elixir compiler that the file contains source code that should be compiled to make it runnable by the BEAM VM.
Let’s write some code and compile it:
defmodule HelloWorld do
def hello do
IO.puts("Hello, world!")
end
end
Save the file as hello_world_123.ex
. Now change to the directory where the file is saved and compile the file with the following command:
# Compile the file to be run on the BEAM VM
elixirc hello_world_123.ex
We should see a new file named Elixir.HelloWorld.beam
in the same directory. This file contains the compiled bytecode for the program, which can be executed on the BEAM VM. If you’ve used languages like Java, this is similar to the .class file generated by the compiler.
To run the program, open a terminal in the current directory and start the iex
shell by typing iex
in your terminal / command prompt. Doing so will open an interactive Elixir shell, which will load all the compiled beam files in the current directory:
# Start the iex shell
iex
You should see an output similar to the following:
Erlang/OTP 26 [erts-14.1.1] [source] [64-bit] [smp:12:12] [ds:12:12:10] [async-threads:1] [jit:ns]
Interactive Elixir (1.15.7) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> HelloWorld.hello() # We can call the function in the iex shell.
Hello, world! # <-- The output is printed here due to calling IO.puts function
:ok # <-- The return value of IO.puts and thus, `HelloWorld.hello` is :ok