Sigils
Sigils in Elixir are a mechanism for working with textual representations using a compact and specialized syntax. They provide a convenient way to create and manipulate different types of data.
Syntax
~<letter><delimiter><content><delimiter><modifiers>
common <delimiter> are ", ', (, [, {, <, /, but you are free to use other chars.
Built-in Sigils
String: ~s and ~S
one reason to use ~s is that it's easier to include double quotes:
~s(double "quotes")
# "double \"quotes\""
uppercased sigils like ~S ignores interpolation or escaping
~S(\n #{})
# "\\n \#{}"
Character List: ~c and ~C
hd(~c"a")
# 97
Regular Expression: ~r and ~R
"a" =~ ~r/^[a-z]$/
# true
Word List: ~w and ~W
~w(split by space)
# ["split", "by", "space"]
~w(a for atom)a
# [:a, :for, :atom]
Date/Time Sigils: ~D, ~T, ~U, ~N
~D[1970-01-01]
# ~D[1970-01-01]
Custom Sigils
defmodule HTMLSigil do
def sigil_h(string, _opts) do
string
|> String.replace("&", "&")
|> String.replace("<", "<")
|> String.replace(">", ">")
end
end
import HTMLSigil
html = ~h(<div>Hello & welcome</div>)
# "<div>Hello & welcome</div>"