Writing Our Own Sigils

Learn to write our own sigils in Elixir.

We'll cover the following

Writing a sigil

Elixir is packed with features that make coding a joy. This chapter contains a smattering of them.

We know by now that we can create strings and regular-expression literals using sigils:

string = ~s{now is the time} 
regex = ~r{..h..}

Have you ever wished you could extend these sigils to add your own specific literal types? You can. When we write a sigil such as ~s{...}, Elixir converts it into a call to the function sigil_s. It passes the function two values:

  • The first is the string between the delimiters.
  • The second is a list containing any lowercase letters that immediately follow the closing delimiter. This second parameter is used to pick up any options we pass to a regular-expression literal, such as ~r/cat/if.

Here’s the implementation of a sigil ~l that takes a multiline string and returns a list containing each line as a separate string. We know that ~l... is converted into a call to sigil_l, so we just write a simple function in the LineSigil module.

Get hands-on with 1200+ tech skills courses.