29

What I want

Some programming languages have a feature for creating multi-line literal strings, for example:

some stuff ... <<EOF
  this is all part of the string
  as is this
  \ is a literal slash
  \n is a literal \ followed by a literal n
  the string ends on the next line
EOF

Question: Does Clojure have something similar to this? I realize that " handles multi-line fine, but I want it to also properly handle \ as a literal.

Thanks!

marco.m
  • 4,573
  • 2
  • 26
  • 41
user1383359
  • 2,673
  • 2
  • 25
  • 32

3 Answers3

21

You might be interested in this little function.

(defn long-str [& strings] (clojure.string/join "\n" strings))

You'd use like so

(long-str "This is the first line. Implicitly I want a new line"
          "When I put a new line in the function call to create a new line")

This does require extra double quotes, but would be closer to what you want.

Brandon Henry
  • 3,632
  • 2
  • 25
  • 30
Virmundi
  • 2,497
  • 3
  • 25
  • 34
  • 2
    Why would you need to create a new function when there's `str`? E.g., `(str "Here is a line.\n" "And a second" "line.")` – celwell Dec 20 '18 at 20:05
  • @celwell to avoid having to explicitly include the new line character like in your example. Since the goal is to make a logical multi-line, \n is annoying. Clojure should support a `` style where it allows breaks across lines like in Go. – Virmundi Dec 21 '18 at 17:42
13

If you need a \ character in the string, just escape it. You don't have to do anything additional to support multiline strings, for example:

"hello \\
there \\
world "

=> "hello \\\nthere \\\nworld"

EDIT :

Now that you've clarified that you don't want to escape the \ character, I'm afraid that Clojure doesn't offer a special syntax for escaping characters, this has been asked before. In essence, Clojure deals with the same string syntax as Java, with no special syntax available.

Community
  • 1
  • 1
Óscar López
  • 232,561
  • 37
  • 312
  • 386
6

If you really want to do this, put your literal string in a txt file and slurp it up with clojure.

(def my-string (slurp "super_long_string.txt"))

If you want to have it be hot-swappable, slurp it in a function.

(defn my-string [] (slurp "something.sql"))

This way every time you change the raw string, you automatically get its current value in your program by calling (my-string).

Brandon Henry
  • 3,632
  • 2
  • 25
  • 30