We'll start with the customary 'Hello World' program. Start the elixir interactive shell using
There are many more intricacies related to function naming in elixir which we'll discuss in coming chapters.
iexAfter the shell starts, use the IO.puts function to "put" the string on the console output. Enter the following in your elixir shell:
IO.puts "Hello world"But in this tutorial we will use Elixir script mode where we will keep Elixir code in a file with extension .ex. So let's keep above code in test.ex file and then in next step we will execute it using elixirc:
IO.puts "Hello world"Let's try to run above program as follows:
$elixirc test.exWhen running above program, it produces following result:
Hello WorldHere we are calling a function IO.puts to output a string to our console. This function can also be called like we do it in C,C++, Java, etc, providing arguments in parentheses following function name:
IO.puts("Hello world")
Comments
Single line comments start with a '#' symbol. There's no multi-line comment, but you can stack multiple comments. For example:#This is a comment in Elixir
Line endings
There are no required line endings like ';' in elixir. However if you want to have multiple statements in the same line, you can use ';'. For example,IO.puts("Hello"); IO.puts("World!")When running above program, it produces following result:
Hello World
Identifiers
Identifiers like variables, function names, etc are used to identify a variable, function, etc. In Elixir 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 valid identifiers in Elixir:var1 variable_2 one_M0r3_variablePlease 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 = 42Also elixir relies 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 won't be imported.
There are many more intricacies related to function naming in elixir which we'll 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 inlist nil else end not or false fn in rescue true when xor __MODULE__ __FILE__ __DIR__ __ENV__ __CALLER__
No comments:
Post a Comment