Want to learn?

Sigils

Do you remember that one of the reasons for creating Elixir was bringing extensibility to Erlang? In this chapter, you will learn how Sigils brings extensibility to textual representations.

Representation

Documentation

As already mentioned, sigil is a mechanism in Elixir for working with textual representations. Every sigil starts with a tilde (~) which is followed by a letter (this is an identification of a sigil) and delimiter (any nonalphanumeric character). Here is a syntax of sigil:

~ + letter + delimiter

For example:
~r/foobar/
~s(hello world)

Extensibility

Sigils are great because of their extensibility, but what does it actually mean? It turns out you can create your own custom sigil with functions (you'll learn soon about functions in Elixir). Since we work on textual representations here, any sigil function must be given a string as the first argument and set of not obligatory options as the second one.

iex> defmodule MySigils do
...> def sigil_i(string, []), do: String.to_integer(string)
...> def sigil_i(string, [?n]), do: -String.to_integer(string)
...> end
iex> import MySigils
iex> ~i(13)
13
iex> ~i(42)n
-42

In this example, we declare sigil responsible for converting a string to an integer, but you can transform such a string in any way you want. That's why sigils are useful. Whenever you identify repetitive tasks performed on a string in your project, you should consider creating sigil out of it. It can speed up the development process and refactor your code in a clean way.

Start a project with your dedicated software house

Top

Contact us

* Required fields

Elo Mordo!Elo Mordo!