Why does the repl treat "\\" different than "\#"?

why does the repl do this

iex(19)> "\\"
"\\"
iex(20)> "\#"
"#"
iex(21)> String.length "\\"
1
iex(22)> String.length "\#"
1
iex(23)> IO.puts "\\"
\
:ok
iex(24)> IO.puts "\#"
#
:ok

why is “\\” special in the repl? when in every other function it isn’t

Backslashes are used for escaping in strings: String — Elixir v1.18.0-dev

I believe this is because the repl is giving you copy/pasteable representations of the output (where it can). # doesn’t need to be quoted but, \ does.

Maybe another example will make it clearer?

Interactive Elixir (1.16.2) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> "\\"
"\\"
iex(2)> "\#"
"#"
iex(3)> "\""
"\""
iex(4)>
3 Likes

This is not iex or “the REPL” treating anything different, this is about the backslash being used to escape things, and elixir, the language, internally normalizes any visual escaping when lexing and parsing string literals. So the relevant AST of "\#" and "#" are simply the same.

Therefore, at the time that this string is inspected, there is nothing to show but the normalized form.

In case of "\\" though, the internal representation is just a single slash. And this is also as what it its printed when doing IO.puts, while the inspection still shows the double slash, as “inspections” are meant to be valid copy/pasteable elixir code most of the time.

4 Likes