Sigils
| ~w word lists | |
| ~r regex | |
| ~s strings | |
| Lowercase escapes |
~w word lists
The sigil ~w builds a list of words without writing quotes and commas around every item. Words split on whitespace, so one short sigil replaces a long literal list. Adding the a modifier turns each word into an atom instead of a string.
words = ~w(apple banana cherry)
IO.inspect(words)
tags = ~w(red green)a
IO.inspect(tags)
["apple", "banana", "cherry"]
[:red, :green]
~r regex
The sigil ~r builds a regular expression without doubling backslashes. Any delimiter works, so parentheses keep the pattern readable when the pattern itself holds slashes. The Regex module then tests strings against the compiled pattern.
pattern = ~r(^hello)
IO.inspect(Regex.match?(pattern, "hello there"))
true
~s strings
The sigil ~s builds a string with interpolation and escape sequences turned on. It shines when the text holds double quotes, since parentheses delimit the string instead of quotes. The uppercase twin ~S keeps everything literal, so interpolation marks stay untouched.
name = "Ada"
IO.puts(~s(hello #{name}))
IO.puts(~S(hello #{name}))
hello Ada
hello #{name}
Lowercase escapes
A lowercase sigil name keeps interpolation and escape sequences active, while the uppercase form switches both off. So ~s interpolates and ~S stays literal, and the same split holds for ~w with ~W and ~r with ~R. Delimiters stay flexible as well: parentheses, brackets, braces, and pipes all work, so pick a pair that stays out of the text.
IO.puts(~s(#{1 + 1}))
IO.puts(~S(#{1 + 1}))
IO.inspect(~w[a b c])
2
#{1 + 1}
["a", "b", "c"]
Next: Binaries and charlists
Article author: Arthur Isaev