Interpolation and escaping in sigils
Besides lowercase sigils, Elixir supports uppercase sigils to deal with escaping characters and interpolation. While both ~s and ~S will return strings, the former allows escape codes and interpolation while the latter does not:
iex> ~s(String with escape codes \x26 #{"inter" <> "polation"})
"String with escape codes & interpolation"
iex> ~S(String without escape codes \x26 without #{interpolation})
"String without escape codes \\x26 without \#{interpolation}"
The following escape codes can be used in strings and char lists:
\"– double quote\'– single quote\\– single backslash\a– bell/alert\b– backspace\d- delete\e- escape\f- form feed\n– newline\r– carriage return\s– space\t– tab\v– vertical tab\0- null byte\xDD- character with hexadecimal representation DD (e.g.,\x13)\x{D...}- character with hexadecimal representation with one or more hexadecimal digits (e.g.,\x{abc13})
Sigils also support heredocs, that is, triple double- or single-quotes as separators:
iex> ~s"""
...> this is
...> a heredoc string
...> """
The most common use case for heredoc sigils is when writing documentation. For example, writing escape characters in documentation would soon become error prone because of the need to double-escape some characters:
@doc """
Converts double-quotes to single-quotes.
## Examples
iex> convert("\\\"foo\\\"")
"'foo'"
"""
def convert(...)
By using ~S, this problem can be avoided altogether:
@doc ~S"""
Converts double-quotes to single-quotes.
## Examples
iex> convert("\"foo\"")
"'foo'"
"""
def convert(...)