Elixir Sigils
A sigil is a short text form that starts with a tilde and builds a value. Each sigil letter builds a different kind of value, such as a word list or a pattern.
A word sigil builds strings, then atoms
The plain word sigil builds strings. The same sigil with the letter a at the end builds atoms.
IO.inspect(~w[one two three])
IO.inspect(~w[red green blue]a)A string sigil fills in values
The ~s sigil builds a string. Values inside the text are worked out and placed in the string.
name = "Ana"
message = ~s(Hello, #{name}. Score: #{3 + 4})
IO.puts(message)Regex functions print match results
The ~r sigil builds the pattern. The three calls below print a boolean, the matches, and the replaced text.
IO.puts(Regex.match?(~r/cat/, "catfish"))
IO.inspect(Regex.scan(~r/\d+/, "a1 b22"))
IO.puts(Regex.replace(~r/\d/, "a1b2", "#"))Example
words = ~w[cat dog catfish bird]
matches = Enum.filter(words, fn word -> Regex.match?(~r/cat/, word) end)
IO.inspect(matches)
IO.puts(~s(Found #{length(matches)} matches))
IO.inspect(~w[win lose]a)Key points
- Word list: ~w[one two three] builds a list of strings with no quotes or commas.
- Atoms: adding the letter a at the end of a word sigil builds a list of atoms instead.
- String: ~s builds a string and fills in values placed inside it, just like a double-quoted string.
- Pattern: ~r/cat/ builds a regular expression, a pattern that describes text to find.
- Match: Regex.match? answers true or false, Regex.scan lists every match, and Regex.replace swaps matches for new text.
- Results: this lesson prints match results only, never the pattern value itself.
In this example, the word sigil builds a list of four words. Enum.filter keeps the words that match the ~r/cat/ pattern, giving cat and catfish. The ~s sigil builds the count message, and a word sigil with the a modifier prints two atoms.
Note
~c"abc" from the basic types lesson is also a sigil, and it builds a charlist.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does ~w[win lose]a build?