Writing Your Own Sigils

You know by now that you 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 you 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 you pass to a regex literal, such as ~r/cat/if.)

Here’s the implementation of a sigil ~l that takes a multiline string and returns a list containing ...

Get Programming Elixir 1.2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.