Book Image

Elixir Cookbook

By : Paulo Pereira
Book Image

Elixir Cookbook

By: Paulo Pereira

Overview of this book

Table of Contents (16 chapters)
Elixir Cookbook
About the Author
About the Reviewers

Creating a word list

In the Using regular expressions recipe, we used a sigil to define a regular expression. A sigil is an alternative way to define structures that have a textual representation within the language.

This recipe will show you the use of the ~W and ~w sigils to create word lists.

Getting ready

Start a new IEx session by entering iex in the command line.

How to do it…

To define word lists using sigils, perform the following steps:

  1. Define a word list with no interpolation:

    iex(1)> ~W(one two "three" ^ @ \| 12345)
    ["one", "two", "\"three\"", "^", "@", "\\|", "12345"]
  2. Define a word list with an interpolation:

    iex(2)> x = 5
    iex(3)> ~w(one two #{x} five#{x} "#{x}")
    ["one", "two", "5", "five5", "\"5\""]

How it works…

When using the ~w and ~W sigils, we don't need to enclose any of the strings in "". We can even use "", and they will be escaped in the resulting list.

In step 1, we use the ~W sigil to define a word list. This sigil does not allow string interpolation. In step 2...