Elixir Sigils - Elixir

What are Sigils in Elixir?

This chapter will give you detailed description of sigils, which is a mechanism to work with textual representations. Sigils start with tilde (~) character followed by a letter (which identifies the sigil) and then a delimiter; optionally, modifiers can be added after the final delimiter.

Regex

Regexes are sigils. Let’s take an example to see how we can use regex in Elixir.

While running above program, it produces following result:

Sigils support 8 different delimiters:

Reason behind supporting different delimiters is that different delimiters can be more suited for different sigils. For example, using parentheses for regular expressions can be a confusing choice as they get mixed with the parentheses inside regex. However, parentheses is easy for other sigils.

Elixir supports Perl compatible regexes and also support modifiers.

Strings, Char lists and Word lists

Other than regexes, Elixir has 3 more in built sigils. Let’s have a look at them.

Strings

~s sigil is used to generate strings, like double quotes are. ~s sigil is useful, for example, when a string contains both double and single quotes:

This sigil generates strings. While running the above program, it produces following result:

Char Lists

~c sigil is used to generate char lists:

While running the above program, it produces following result:

Word lists

~w sigil is used for generating lists of words (words are just regular strings). Inside of ~w sigil, words are separated by whitespace.

While running the above program, it produces following result:

~w sigil also accepts c, s and a modifiers (for char lists, strings and atoms, respectively), which specify the data type of the elements of the resulting list:

While running the above program, it produces following result:

Interpolation and escaping in sigils

In addition to lowercase sigils, Elixir also supports uppercase sigils to deal with escaping characters and interpolation. While both ~s and ~S return strings, former allows escape codes and interpolation while the latter does not. Let’s look at an example:

Custom Sigils

You can easily create our own custom sigils. In this example, we will create a sigil to convert a string to uppercase.

While running the above program, it produces following result:

First we define a module called CustomSigil and within that module, we will creat a function called sigil_u. As there is no existing ~u sigil in the existing sigil space, we will use it. _u indicates that we wish to use u as the character after the tilde. Function definition should take two arguments, an input and a list.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Elixir Topics