2

What is the right way to escape control characters in Erlang?

I do:

[EscapedString] = io_lib:format("~p", [Str]).

It works as I expect for \t and \n characters:

io_lib:format("~p", ["str\ning"]).

["\"str\\ning\""]

But for \a :

io_lib:format("~p", ["str\aing"]).

["\"straing\""]

and

io_lib:format("~p", ["a\x07"]).

[[91,["97",44,"7"],93]]

I need to get "\"str\\aing\"" string and in file it should look like "str\aing".

Thank you for your help :)

  • In corresponding to [documentation](http://erlang.org/doc/reference_manual/data_types.html#id72152) this sequence doesn't escaping so if you need another behaviour just write own transforming function. –  Apr 05 '18 at 09:22
  • You probably want to use `~n` instead of `\n`--because erlang will convert `~n` to the proper newline sequence for the OS the program is running on. Unlike in other languages, erlang does not do any newline conversions for `\n`. – 7stud Apr 05 '18 at 22:43

1 Answers1

3

'a' is not a control character, so "\a" yields the same string as "a". If you really want a backslash in the result, you need to escape the backslash itself: "str\\aing".

Use lists:flatten(io_lib:format(...)) if you want the result to always be a flat string rather than a nested io-list, as in your last example.

RichardC
  • 10,412
  • 1
  • 23
  • 24
  • I don't think the output in your post is what you wanted for the escaped backslash. Just put code tags around it. – 7stud Apr 05 '18 at 22:46