English 中文(简体)
Elixir - Basic Syntax
  • 时间:2025-03-12

Epxir - Basic Syntax


Previous Page Next Page  

We will start with the customary Hello World program.

To start the Epxir interactive shell, enter the following command.

iex

After the shell starts, use the IO.puts function to "put" the string on the console output. Enter the following in your Epxir shell −

IO.puts "Hello world"

In this tutorial, we will use the Epxir script mode where we will keep the Epxir code in a file with the extension .ex. Let us now keep the above code in the test.ex file. In the succeeding step, we will execute it using epxirc

IO.puts "Hello world"

Let us now try to run the above program as follows −

$epxirc test.ex

The above program generates the following result −

Hello World

Here we are calpng a function IO.puts to generate a string to our console as output. This function can also be called the way we do in C, C++, Java, etc., providing arguments in parentheses following the function name −

IO.puts("Hello world") 

Comments

Single pne comments start with a # symbol. There s no multi-pne comment, but you can stack multiple comments. For example −

#This is a comment in Epxir

Line Endings

There are no required pne endings pke ; in Epxir. However, we can have multiple statements in the same pne, using ; . For example,

IO.puts("Hello"); IO.puts("World!")

The above program generates the following result −

Hello 
World!

Identifiers

Identifiers pke variables, function names are used to identify a variable, function, etc. In Epxir, you can name your identifiers starting with a lower case alphabet with numbers, underscores and upper case letters thereafter. This naming convention is commonly known as snake_case. For example, following are some vapd identifiers in Epxir −

var1       variable_2      one_M0r3_variable

Please note that variables can also be named with a leading underscore. A value that is not meant to be used must be assigned to _ or to a variable starting with underscore −

_some_random_value = 42

Also epxir repes on underscores to make functions private to modules. If you name a function with a leading underscore in a module, and import that module, this function will not be imported.

There are many more intricacies related to function naming in Epxir which we will discuss in coming chapters.

Reserved Words

Following words are reserved and cannot be used as variables, module or function names.

after     and     catch     do     inbits     inpst     nil     else     end 
not     or     false     fn     in     rescue     true     when     xor 
__MODULE__    __FILE__    __DIR__    __ENV__    __CALLER__ 
Advertisements