In, for example, the Bash scripting language, the following creates a string called $VAR
which begins at the first "
quote and continues until the next unescaped "
quote.
$VAR="
hello
world!
this string preserves all
whitespace"
This makes it very easy to write multiline strings without concatentation or a million annoying \n
s everywhere, and it makes the parser very easy to write (speaking from experience) because you can just gobble everything between unescaped quotes with a regex like "([^"\\]*(?:\\.[^"\\]*)*)"
or so.
Bash is (hopefully!) not a mission-critical or systems-programming language, but it is a systems-scripting language intended for *nx boxes on which everything is text, so perhaps it's apt.
Recall that Bash is written in C, and so this string is (probably) stored as \n\thello\nworld\n
etc, but the point is the source written by the programmer (and the above is far more readable).
Many (I daresay C-influenced) "proper" Languages Used For Real Purposes find some unknown problem with allowing strings to contain literal newlines, and thus require one or more of the following:
escape sequences
\n
(which get compiled into\r\n
on Windows)special syntax (
""" multiline string """
in Py,`multiline string`
in Go, orR" raw string literal "
in C++11, etc)special functions to write newlines (Forth's
CR
, for example, although Forth gets a pass because it knows squat about strings)
I do not understand why more languages don't allow strings to be "implicitly" multiline.
Pros:
ease of use & practicality, clearer code, etc
simpler, more straightforward and thus more maintainable parser (at least, for hand-written ones)
Cons:
may make some code less readable, if abused
?
Is there an explicit reason this is the case, or has it just been blindly(?) adopted from C like so many other things? Moreover, if I'm writing a parser or designing a language, is there a compelling argument as to why I should restrict string literals to a single line?
"a" "b"
in the source code is compiled as"ab"
, which makes it easy to have a large string that is distributed over multiple lines.