Here document: Difference between revisions

(→‎{{header|Perl 6}}: showcase the indentation removal in the intro example.)
 
(93 intermediate revisions by 46 users not shown)
Line 1:
{{task}} [[Category: Syntax elements]]
{{omit from|BBC BASIC}}
{{omit from|Déjà Vu}}
{{omit from|Gambas}}
{{omit from|GW-BASIC}}
{{omit from|MATLAB|MATLAB has no multiline string literal functionality}}
 
A   ''here document''   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text.
 
Line 15 ⟶ 9:
;Task:
Demonstrate the use of   ''here documents''   within the language.
 
;Related task:
*   [[Documentation]]
<br><br>
 
{{omit from|Delphi}}
 
=={{header|11l}}==
11l does not have here-docs. It does however have raw strings which can be used similarly.
<syntaxhighlight lang="11l">print(‘
here
doc
’)</syntaxhighlight>
 
=={{header|8th}}==
Multiline strings are simply parsed using "quote", which parses first a character to use as a separator, and scans until that character is found:
<langsyntaxhighlight lang="forth">
quote *
Hi
there
* .
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 30 ⟶ 36:
there
</pre>
 
=={{header|Ada}}==
 
Line 35 ⟶ 42:
A workaround is to use containers of strings:
 
<langsyntaxhighlight Adalang="ada">with Ada.Containers.Indefinite_Vectors, Ada.Text_IO;
 
procedure Here_Doc is
Line 54 ⟶ 61:
Ada.Text_IO.Put_Line(Document.Element(I));
end loop;
end Here_Doc;</langsyntaxhighlight>
 
{{out}}
Line 69 ⟶ 76:
It can be crudely achieved using an array of strings:
 
<langsyntaxhighlight lang="algol68">#!/usr/local/bin/a68g --script #
 
[]STRING help = (
Line 86 ⟶ 93:
"Dammit. Janet, I love you."
))
</syntaxhighlight>
</lang>
 
{{out}}
Line 99 ⟶ 106:
I've one thing to say and that's ...
Dammit. Janet, I love you.</pre>
 
=={{header|APL}}==
{{works with|GNU APL}}
See the GNU APL docs: [https://www.gnu.org/software/apl/apl.html#Section-2_002e1 2.1.4 Helpful Features for Scripting]
<syntaxhighlight lang="apl">
BODY←⎕INP 'END-OF-⎕INP'
First line
Second line
Third line
...
END-OF-⎕INP
</syntaxhighlight>
A related concept is multi-line strings (note the 6 space indent of APL interactive input vs. output):
<syntaxhighlight lang="apl">
]boxing 8
s ← """
→ abc
→ def
→ GHIJK
→ """
s</syntaxhighlight>
{{out}}
<pre>┌┌→────────────────────────────────────────┐
│┌→──────┐ ┌→────────┐ ┌⊖┐ ┌→────────────┐ │
││ abc│ │ def│ │ │ │ GHIJK│ │
│└───────┘ └─────────┘ └─┘ └─────────────┘ │
└∊─────────────────────────────────────────┘</pre>
 
=={{header|Applesoft BASIC}}==
Strings are limited to 255 characters. The double quote character delimits strings, so double quote cannot be embedded directly. The double quote can be included in a DATA statement if the text is not wrapped in quotes. Most control characters, with the exception of Return ^M, Backspace ^H, Forward-space ^U and Escape ^[, can be typed into strings. Control characters are not usually visible. The line feed character ^J moves the cursor position down one line, and the ^G character is audible!
<syntaxhighlight lang="gwbasic"> 0 Q$ = CHR$ (34)
1 M$ = CHR$ (13)
2 PRINT Q$"Oh, Danny Boy,"M$"The pipes, the pipes are calling"M$"From glen to glen and down the mountainside"Q$</syntaxhighlight>
There are tools and tricks to embed control characters like Return directly into the program.
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program heredoc.s */
 
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
 
.equ BUFFERSIZE, 100
 
/* Initialized data */
.data
szMessString: .asciz "String :
ABCD
EFGH TAB \n"
 
szCarriageReturn: .asciz "\n"
 
/* UnInitialized data */
.bss
 
/* code section */
.text
.global main
main:
 
ldr r0,iAdrszMessString @ display message
bl affichageMess
 
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc 0 @ perform system call
iAdrszMessString: .int szMessString
iAdrszCarriageReturn: .int szCarriageReturn
 
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registers
mov r2,#0 @ counter length */
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call system
pop {r0,r1,r2,r7,lr} @ restaur registers
bx lr @ return
</syntaxhighlight>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">print {:
The “Red Death” had long devastated the country.
No pestilence had ever been so fatal, or so hideous.
 
Blood was its Avator and its seal—
the redness and the horror of blood.
 
There were sharp pains,
and sudden dizziness,
and then profuse bleeding at the pores,
with dissolution.
The scarlet stains upon the body
and especially upon the face of the victim,
were the pest ban
which shut him out from the aid
and from the sympathy of his fellow-men.
 
And the whole seizure,
progress and termination of the disease,
were the incidents of half an hour.
:}</syntaxhighlight>
 
{{out}}
 
<pre> The “Red Death” had long devastated the country.
No pestilence had ever been so fatal, or so hideous.
 
Blood was its Avator and its seal—
the redness and the horror of blood.
 
There were sharp pains,
and sudden dizziness,
and then profuse bleeding at the pores,
with dissolution.
The scarlet stains upon the body
and especially upon the face of the victim,
were the pest ban
which shut him out from the aid
and from the sympathy of his fellow-men.
 
And the whole seizure,
progress and termination of the disease,
were the incidents of half an hour.</pre>
 
=={{header|AutoHotkey}}==
AutoHotkey uses "continuation sections" for literal text:
 
<langsyntaxhighlight AutoHotkeylang="autohotkey">MyVar = "This is the text inside MyVar"
MyVariable =
(
Line 111 ⟶ 261:
Variable references such as %MyVar% are expanded.
)
MsgBox % MyVariable</langsyntaxhighlight>
 
=={{header|AWK}}==
 
The awk extraction and reporting language does not provide any markup facility for embedding here documents within an awk script. The awk utility is really a helper tool often used from within the Unix shell. The Unix shell in which awk scripts are usually embedded does support the use of here documents, and the way that here documents are used within the shell make them ideal for passing to awk as is, without the need for an additional facility in awk.
 
=={{header|BQN}}==
Works in: [[CBQN]]
 
The default string syntax in BQN allows multiline strings. Strings start and end with a double quote, and quotes within the text can be escaped by typing two quotes.
 
<syntaxhighlight lang="bqn">•Out "dsdfsdfsad
""fsadf""sdf"</syntaxhighlight><syntaxhighlight lang="text">dsdfsdfsad
"fsadf"sdf</syntaxhighlight>
 
=={{header|Bracmat}}==
Strings in Bracmat can continue over many lines. They start and end with a quote. Quotes in the text must be escaped with a reverse solidus, like the reverse solidus itself.
 
<langsyntaxhighlight lang="bracmat">( {Multiline string:}
"
Second line
Line 129 ⟶ 288:
& out$("Multiline string:")
& out$(!stringA)
)</langsyntaxhighlight>
Output:
<pre>Multiline string:
Line 138 ⟶ 297:
A backslash: \
</pre>
 
=={{header|BaCon}}==
<syntaxhighlight lang="freebasic">
'--- we dont have a print here doc built-in command in BaCon
'--- we can get the end result like this with the newline NL$
 
PRINT "To use Bacon your system must have either Korn Shell, or ZShell, or Bourne Again Shell (BASH) available." NL$ \
"If none of these shells are available on your platform, download and install the free Public Domain Korn Shell which can" NL$ \
"execute BaCon also. Furthermore BaCon also works with a newer Kornshell implementation like the MirBSD Korn Shell." NL$ NL$ \
"BaCon intends to be a programming aid in creating tools which can be compiled on different platforms" NL$ \
"(including 64bit environments). It tries to revive the days of the good old BASIC." NL$
 
</syntaxhighlight>
Output:
<pre>To use Bacon your system must have either Korn Shell, or ZShell, or Bourne Again Shell (BASH) available.
If none of these shells are available on your platform, download and install the free Public Domain Korn Shell which can
execute BaCon also. Furthermore BaCon also works with a newer Kornshell implementation like the MirBSD Korn Shell.
 
BaCon intends to be a programming aid in creating tools which can be compiled on different platforms
(including 64bit environments). It tries to revive the days of the good old BASIC.</pre>
 
 
=={{header|BASIC}}==
BASIC no tiene heredocs ni cadenas de varias líneas. Una solución
alternativa es unir varias cadenas en una línea con CHR$(10).
<syntaxhighlight lang="basic">
text1$ = " " + CHR$(10) + "<<'FOO' " + CHR$(10) + " 'jaja', `esto`" + CHR$(10) + " <simula>" + CHR$(10) + " \un\" + CHR$(10) + " ${ejemplo} de 'heredoc'" + CHR$(10) + " en QBASIC."
 
text2$ = "Esta es la primera línea." + CHR$(10) + "Esta es la segunda línea." + CHR$(10) + "Esta 'línea' contiene comillas."
 
PRINT text1$
PRINT
PRINT text2$
END
</syntaxhighlight>
{{out}}
<pre>
Igual que la entrada de FreeBASIC.
</pre>
 
 
=={{header|BASIC256}}==
BASIC256 no tiene heredocs ni cadenas de varias líneas. Una solución
alternativa es unir varias cadenas en una línea con chr(10).
<syntaxhighlight lang="basic256">
text1$ = " " & chr(10) & "<<#FOO# " & chr(10) & " #jaja#, `esto`" & chr(10) & " <simula>" & chr(10) & " \un\" & chr(10) & " ${ejemplo} de 'heredoc'" & chr(10) & " en BASIC256."
 
text2$ = "Esta es la primera linea." & chr(10) & "Esta es la segunda linea." & chr(10) & "Esta 'linea' contiene comillas."
 
print text1$
print
print text2$
end
</syntaxhighlight>
{{out}}
<pre>
Igual que la entrada de FreeBASIC.
</pre>
 
=={{header|Blade}}==
<syntaxhighlight lang="blade">echo 'All strings
support
multiline
in Blade'</syntaxhighlight>
{{out}}
<pre>
All strings
support
multiline
in Blade
</pre>
 
 
=={{header|C sharp}}==
C# has a string literal call which is used for heredoc functionality
 
<syntaxhighlight lang="c sharp">using System;
 
class Program
{
static void Main(string[] args)
{
Console.Write(@"
multiline
strings are easy
to put together
in C#");
}
}</syntaxhighlight>
 
=={{header|C++}}==
Line 143 ⟶ 391:
C++11 raw string literals are similar to heredocs, except there is no newline after the opening token or before the ending token (unless you actually want newlines there).
 
<langsyntaxhighlight lang="cpp">#include <iostream> // Only for cout to demonstrate
 
int main()
Line 160 ⟶ 408:
or recognized, and all whitespace is preserved.
)EOF";
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
C# has a string literal call which is used for heredoc functionality
 
<lang C sharp>using System;
 
class Program
{
static void Main(string[] args)
{
Console.Write(@"
multiline
strings are easy
to put together
in C#");
}
}</lang>
 
=={{header|Clojure}}==
Line 187 ⟶ 418:
CoffeeScript borrows the triple-quoted string syntax from Python. Note that these strings strip leading whitespace in CoffeeScript, to allow you to neatly align the heredoc string.
 
<langsyntaxhighlight lang="coffeescript">myDoc = '''
Single-quoted heredocs allows no '#{foo}' interpolation.
This behavior is similar to single-quoted strings.
Line 197 ⟶ 428:
"""
 
console.log doc2</langsyntaxhighlight>
 
{{out}}
Line 208 ⟶ 439:
 
Note how the extra indentation in the third line of doc2 is preserved.
 
=={{header|Common Lisp}}==
 
[https://github.com/e-user/cl-heredoc cl-heredoc] provide read-macro for heredoc:
 
<syntaxhighlight lang="lisp">;; load cl-heredoc with QuickLisp
(ql:quickload 'cl-heredoc)
 
;; use #>xxx>yyyyyyyy!xxx as read-macro for heredoc
(set-dispatch-macro-character #\# #\> #'cl-heredoc:read-heredoc)
 
;; example:
(format t "~A~%" #>eof1>Write whatever (you) "want",
no matter how many lines or what characters until
the magic end sequence has been reached!eof1)
</syntaxhighlight>
{{out}}
<pre>
Write whatever (you) "want",
no matter how many lines or what characters until
the magic end sequence has been reached!
NIL
</pre>
 
Note: <code>NIL</code> is the return value of function <code>format</code> when first argument is <code>t</code>
 
=={{header|Crystal}}==
<syntaxhighlight lang="ruby">puts <<-DOC
this is a heredoc
it preserves indents and newlines
the DOC identifier is completely arbitrary
it can be lowercase, a keyword, or even a number (but not a float)
DOC</syntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.string;
 
void main() {
Line 230 ⟶ 494:
 
// std.string.outdent is used to remove the four spaces indent.
}</langsyntaxhighlight>
{{out}}
<pre>a string that you "don't" have to escape
Line 240 ⟶ 504:
=={{header|DWScript}}==
Double-quotes (") denote a multi-line string, to include a double-quote in such a string, you need to double it.
<langsyntaxhighlight lang="delphi">PrintLn("This is
a multiline
""string""
sample");</langsyntaxhighlight>
{{out}}
<pre>This is
Line 249 ⟶ 513:
"string"
sample</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight>
# The here-document is not here, but at the end of the program
repeat
s$ = input
until error = 1
print s$
.
input_data
This is a 'raw' string with the following properties:
- indention is preserved,
- an escape sequence such as a quotation mark "\\" is interpreted literally, and
- interpolation such as %(a) is also interpreted literally.
- """ is also interpreted literally.
 
`Have fun!`
</syntaxhighlight>
{{out}}
<pre>
This is a 'raw' string with the following properties:
- indention is preserved,
- an escape sequence such as a quotation mark "\\" is interpreted literally, and
- interpolation such as %(a) is also interpreted literally.
- """ is also interpreted literally.
 
`Have fun!`
</pre>
 
=={{header|EchoLisp}}==
Line 302 ⟶ 594:
=={{header|Elixir}}==
In Elixir, one can use either a pair of triple single-quotation marks or a pair of triple double-quotation marks, but in both cases, string interpolation occurs:
<langsyntaxhighlight lang="elixir">IO.puts """
привет
мир
"""</langsyntaxhighlight>
produces:<langsyntaxhighlight lang="sh">привет
мир</langsyntaxhighlight>
 
Here is an illustrative iex transcript:
<langsyntaxhighlight lang="elixir">iex(1)> a=2
2
iex(2)> '''
Line 320 ⟶ 612:
** (SyntaxError) iex:3: heredoc start must be followed by a new line after '''
iex(3)></langsyntaxhighlight>
 
=={{header|Erlang}}==
Multiline strings look like this in the Erlang shell:
<syntaxhighlight lang="erlang">
<lang Erlang>
2> S = " ad
2> 123
Line 332 ⟶ 624:
123
the end
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
Line 347 ⟶ 639:
 
=={{header|Factor}}==
Factor strings surround by '"' are multiline, but accept escape sequences (like "\n", "\uxxxxxxxx"). Strings surrounded by '"""' don't have to escape '"'. Use HEREDOC: (and other variants, like <pre>[[</pre>) for verbatim text
<langsyntaxhighlight lang="factor">" a multiline
string\n(with escape sequences: \u{greek-capital-letter-sigma})
"
"""this is "easier".."""
 
 
 
HEREDOC: EOF
this
is not \n escaped at all
EOF</langsyntaxhighlight>
 
[[ this also works , but needs a space at the start (but not the end)]]
[[this won't work]]
[=[ this works like [[, but I can write [[ and ]] without restriction]=]
[==[ it keeps going]==]
[===[ like this]===]
[====[ for a while]====]
 
=={{header|Forth}}==
 
===version 1===
{{works with|GForth}}
<langsyntaxhighlight Forthlang="forth">\ GForth specific words:
\ under+ ( a b c -- a+c b) , latest ( -- nt ) , name>string ( nt -- ca u )
\ Should not be a problem to modify it to work with other Forth implementation:
Line 386 ⟶ 691:
BEGIN refill >R
get_line 2dup EOD compare
R> AND \ notEOD && input-stream ->
WHILE rot $!+ EOL!+
REPEAT 2drop
Line 406 ⟶ 711:
>> RABBIT
RABBIT
ALICE type ." --" cr RABBIT type</langsyntaxhighlight>
 
<pre>
Line 417 ⟶ 722:
conversation?'
--
</pre>
 
===version 2===
{{works with|GForth}}
Here's a slightly different implementation, with less stack juggling. It does not echo linefeeds in interactive mode, but that can easily be added.
 
It's written to works with Forth's default implementation of counted strings. Those are limited to 255 characters, which is fine in many cases, but on the short side for here documents, so therefore we temporarily redefine them to use a full cell for size (16 bits would probably be ideal) while compiling the here document words.
<syntaxhighlight lang="forth">get-current get-order wordlist swap 1+ set-order definitions
: place over >r rot over cell+ r> move ! ;
: +place 2dup >r >r dup @ cell+ + swap move r> r> dup @ rot + swap ! ;
: count dup cell+ swap @ ;
set-current
 
CREATE eol 10 C, DOES> 1 ;
CREATE eod 128 ALLOT DOES> count ;
: seteod 0 parse ['] eod >body place ;
: start 0 0 here place ;
: read refill 0= IF abort" Unterminated here document" THEN ;
: ~end source eod compare ;
: store source here +place eol here +place ;
: slurp BEGIN read ~end WHILE store REPEAT refill drop ;
: totalsize here count + here - ;
: finish totalsize ALLOT align ;
: << seteod start slurp finish DOES> count ;
previous
 
( Test )
 
CREATE Alice << ~~ end ~~
They got a building down New York City, it’s called Whitehall Street,
Where you walk in, you get injected, inspected, detected, infected,
Neglected and selected.
~~ end ~~
 
Alice type bye</syntaxhighlight>
 
{{out}}
<pre>
They got a building down New York City, it’s called Whitehall Street,
Where you walk in, you get injected, inspected, detected, infected,
Neglected and selected.
</pre>
 
=={{header|Fortran}}==
In Fortran, spaces outside text literals are nowhere significant, not even within words, so that <code>GOTO = G OTO = GO TO</code> and there are no reserved words either so GOTO might be the name of a variable as well and both can be used in the same source. Statements were originally specified with a special format: columns one to five were for statement labels (integers only, not zero), column six specified a continuation line if not blank or zero, and columns 73-80 were for sequence numbers in case you dropped the deck of cards. Thus, source was found in columns 7-72, and layout of the source could be varied without effect on the results. Originally, the only way to produce text in the output (as for annotating the numerical results) was via the "Hollerith" format code, of the form nH where n specified the ''exact'' count of characters following the H. Any characters. Miscounts would cause a syntax error - if you were lucky! Happily, a quoted literal syntax was soon introduced, using apostrophes as delimiters with two apostrophes in a row signifying a contained apostrophe. Later, either an apostrophe or a double quote could be used to start a text string (and the same one must be used to end it) so that if one or the other were desired within a text literal, the other could be used as its delimiters. If both were desired, then there would be no escape from doubling for one.
 
Producing a source file containing a block of text that will be presented as output in the same layout (new lines and all) is only possible if the added layout stuff (generating the required new line starts) and delimiters in the source are disregarded. But if one accepts a few constraints, the following shows a possible approach:
<syntaxhighlight lang="fortran">
<lang Fortran>
INTEGER I !A stepper.
CHARACTER*666 I AM !Sufficient space.
I AM = "<col72
C 111111111122222222223333333333444444444455555555556666666666
Line 436 ⟶ 782:
 
Chug through the text blob.
DO I = 0,600,66 !Known length.
WRITE (6,1) I AM(I + 1:I + 66) !Reveal one line.
1 FORMAT (A66) !No control characters are expected.
END DO !On to the next line.
END
</syntaxhighlight>
</lang>
With old-style fixed-format source, rather amusingly there is space for sixty-six characters of text per line and so this is the canvas. Any usage of tab characters must be resolved into spaces (and some compilers count up to 72 oddly when tabs are involved) and likewise with new lines. A surprise was provided to an old-time card flapper when it became apparent that trailing spaces were ''not'' being incorporated into the text literal unless the "<col72" markers were appended to column seventy-two of the source. An old-time card deck copied to disc and with the sequence numbers in columns 73-80 removed (as no-one is going to drop a disc file so some storage space can be saved) might thereby compile incorrectly! Similarly, the source text highlighter here does not fully recognise the odd tricks available for Fortran syntax, apparently deeming the comments a part of a text literal. The F90 compiler's highlighting does, and shows that text beyond column 72 is not Fortran code.
 
Line 454 ⟶ 800:
 
</pre>
 
=={{header|Free Pascal}}==
In Pascal, the only forbidden character in string literals is the newline character.
However, as of 2019‑09‑06 in a trunk version of the FPC (Free Pascal compiler) support for string literals spanning multiple lines can be enabled.
 
 
=={{header|FreeBASIC}}==
FreeBASIC no tiene heredocs ni cadenas de varias líneas. Una solución
alternativa es unir varias líneas con NL, LF, \n o Chr(10).
<syntaxhighlight lang="freebasic">
Dim As String text1 = " " & Chr(10) & _
"<<'FOO' " & Chr(10) & _
" 'jaja', `esto`" & Chr(10) & _
" <simula>" & Chr(10) & _
" \un\" & Chr(10) & _
!" ${ejemplo} de \"heredoc\"" & Chr(10) & _
" en FreeBASIC."
 
Dim As String text2 = "Esta es la primera linea." & Chr(10) & _
"Esta es la segunda linea." & Chr(10) & _
!"Esta \"linea\" contiene comillas."
 
Print text1
Print Chr(10) + text2
Sleep
</syntaxhighlight>
{{out}}
<pre>
<<'FOO'
'jaja', `esto`
<simula>
\un\
${ejemplo} de "heredoc"
en FreeBASIC.
 
Esta es la primera linea.
Esta es la segunda linea.
Esta "linea" contiene comillas.
</pre>
 
 
=={{header|Frink}}==
Frink does not have awkward here-docs. Triple-quoted strings serve the same purpose, but more concisely. (The Perl, PHP, etc. syntax for here-documents is a violation of the "define everything at most once" principle of software engineering.) Variable interpolation is allowed within triple-quoted strings.
<langsyntaxhighlight lang="frink">
lyrics = """Oh, Danny Boy,
The pipes, the pipes are calling
From glen to glen and down the mountainside"""
</syntaxhighlight>
</lang>
 
=={{header|Genie}}==
Genie includes triple quoted verbatim strings and "at" quoted template strings, which can be used as Heredoc data in source. Given the limitation of terminating quotes not being a user defined sequence, inner quotations will need to be escaped or transcluded.
 
<syntaxhighlight lang="genie">[indent=4]
/*
Here documents, as template and verbatim strings in Genie
valac heredoc.gs
*/
init
test:string = "Genie string"
 
var multilineString = """
this is a $test
"""
 
var templateString = @"
this is a $test template
with math for six times seven = $(6 * 7)
"
 
stdout.printf("%s", multilineString)
stdout.printf("%s", templateString)</syntaxhighlight>
 
{{out}}
<pre>prompt$ valac heredoc.gs
prompt$ ./heredoc
 
this is a $test
 
this is a Genie string template
with math for six times seven = 42</pre>
 
=={{header|Go}}==
Go does not have here documents. Multiline string literals serve this purpose.
 
<langsyntaxhighlight lang="go">var m = ` leading spaces
 
and blank lines`</langsyntaxhighlight>
 
=={{header|Groovy}}==
Line 475 ⟶ 893:
===Multi-line String literal===
The literal text, preserving lines and spacing
<langsyntaxhighlight lang="groovy">println '''
Time's a strange fellow;
more he gives than takes
Line 482 ⟶ 900:
losing, gaining
--love! if a world ends
'''</langsyntaxhighlight>
 
{{out}}
Line 496 ⟶ 914:
===Multi-line GString expression===
Like single-line GString expressions, any subexpression delimited with ${ } is substituted with its "toString()" value. Preserves lines and spacing outside of the subexpressions.
<langsyntaxhighlight lang="groovy">def expired='defunct'
def horse='stallion'
def christ='Jesus'
Line 513 ⟶ 931:
how do you like your blueeyed boy
Mister Death
"""</langsyntaxhighlight>
 
{{out}}
Line 533 ⟶ 951:
=={{header|Haskell}}==
 
You could use [https://hackage.haskell.org/package/raw-strings-qq raw-strings-qq], or alternatively:
<lang Haskell>
 
<syntaxhighlight lang="haskell">
 
main :: IO ()
Line 552 ⟶ 972:
]
 
</syntaxhighlight>
</lang>
 
Output:
Line 569 ⟶ 989:
 
=={{header|J}}==
<langsyntaxhighlight lang="j">here=:0 :0
0 :0 will be replaced by the text on the following lines.
This is three tokens: two instances of the number 0 and
Line 608 ⟶ 1,028:
note that this mechanism is significantly more verbose than using
the underlying 0 :0 mechanism directly.
)
)</lang>
 
also_here=: {{)n
J902 introduced {{ blocks which may be {{ nested }} arbitrarily }} to
the J interpreter. This includes {{)n blocks which are here documents.
These {{)n blocks are not further nestable (they represent
literal text with no internal structure), and the terminating }}
must appear at the beginning of a line (or on the same line as
the opening {{)n -- but that would not be a "here doc").
 
If text does not appear after the )n on the initial line, the
initial (first) linefeed does not appear in the here doc. If
text follows the {{)n, that text (and optional newline) would
be included.
}}</syntaxhighlight>
 
=={{Header|Java}}==
[[User:Sjharper79|Sjharper79]] ([[User talk:Sjharper79|talk]])
 
====Compatibility====
The Java feature 'Text Blocks' is only available with JDK 15 and above.
 
====Syntax====
You must include a newline character after the opening """, you cannot include any Strings after the opening """. The closing """ does not have to be on its own line.
 
See [https://www.demo2s.com/java/java-17-string-block-for-multiline-java-string.html Java 17 String block for Multiline Java String].
 
<syntaxhighlight lang=java>
package rosettacode.heredoc;
public class MainApp {
public static void main(String[] args) {
String hereDoc = """
This is a multiline string.
It includes all of this text,
but on separate lines in the code.
""";
System.out.println(hereDoc);
}
}
</syntaxhighlight>
 
====Output====
<pre>
This is a multiline string.
It includes all of this text,
but on separate lines in the code.
</pre>
 
=={{header|JavaScript}}==
===ES6===
ES6 introduced template literals. These are string literals that suport multi-line text and can include
interpolated expressions using ${···} syntax. It is indicated with the backtich character [`]
<syntaxhighlight lang="javascript">const myVar = 123;
const tempLit = `Here is some
multi-line string. And here is
the value of "myVar": ${myVar}
That's all.`;
console.log(tempLit)
</syntaxhighlight>
 
<pre>Here is some
multi-line string. And here is
the value of "myVar": 123
That's all.</pre>
 
=={{header|jq}}==
No special syntax is required to support "here documents" in jq in that any JSON string, and indeed any string specifier (as explained below), can be presented using a multiline format.
 
For example, consider:<langsyntaxhighlight lang="jq">
def s:
"x
Line 619 ⟶ 1,102:
z";
 
s</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight lang="sh">$ jq -n s.jq
"x\ny\nz"</langsyntaxhighlight>
 
String specifiers, that is possibly non-JSON strings which incorporate references to jq expressions, are handled in the same way. For example, the following program produces the same result:
<langsyntaxhighlight lang="jq">def specifier(a):
"x
\(a)
z";
 
specifier("y")</langsyntaxhighlight>
 
Most control characters, such as Control-A and Control-Z, can also be presented literally, but the RosettaCode.org editor disallows them in general, so the next example only shows an embedded literal tab:
<langsyntaxhighlight lang="jq">"a
tab: end
parens:()
single quotation mark:'
double quotation mark must be escaped:\"
b
d"</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">"a\ntab:\tend\nparens:()\nsingle quotation mark:'\ndouble quotation mark must be escaped:\"\nb\nd"</langsyntaxhighlight>
 
=={{header|Julia}}==
Like Python, Julia has triple-quoted string literals, which are similar to here-docs:
 
<langsyntaxhighlight lang="julia">print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")</langsyntaxhighlight>
 
=={{header|Kotlin}}==
Kotlin's 'raw string literals' behave in a similar way to 'here' documents in that line breaks, indentation and other whitespace is preserved within the string. They are distingished from normal strings by being surrounded by triple quote characters rather than by single quotes.
 
Escaped characters (such as \n, \t etc.) do not have a special meaning and so are treated literally.
 
It's also possible to embed variables and other expressions in a raw string literal using Kotlin's string interpolation facilities.
 
Here's an example of all this:
<syntaxhighlight lang="scala">// version 1.1.0
 
fun main(args: Array<String>) {
val ev = "embed variables"
 
val here = """
This is a raw string literal
which does not treat escaped characters
(\t, \b, \n, \r, \', \", \\, \$ and \u)
specially and can contain new lines,
indentation and other whitespace
within the string.
"Quotes" or doubled ""quotes"" can
be included without problem but not
tripled quotes.
 
It's also possible to $ev
in a raw string literal using string
interpolation.
 
If you need to include a
literal ${'$'} sign in a raw string literal then
don't worry you've just done it!
"""
 
println(here)
}</syntaxhighlight>
 
{{out}}
<pre>
This is a raw string literal
which does not treat escaped characters
(\t, \b, \n, \r, \', \", \\, \$ and \u)
specially and can contain new lines,
indentation and other whitespace
within the string.
 
"Quotes" or doubled ""quotes"" can
be included without problem but not
tripled quotes.
 
It's also possible to embed variables
in a raw string literal using string
interpolation.
 
If you need to include a
literal $ sign in a raw string literal then
don't worry you've just done it!
 
</pre>
 
=={{header|Lambdatalk}}==
Lambdatalk inverts the standard evaluation process, nothing is evaluated out of S-expressions {first rest}.
 
<syntaxhighlight lang="scheme">
1) defining a variable:
{def myVar 123}
 
2) defining some text:
Here is some
multi-line string. And here is
the value of "myVar": '{myVar}
That's all.
 
3) displays :
 
Here is some
multi-line string. And here is
the value of "myVar": 123
That's all.
</syntaxhighlight>
 
=={{header|langur}}==
Use a block modifier on a string literal using the qs or QS form to generate a blockquote. The block modifier must be the last modifier.
 
<syntaxhighlight lang="langur">val .s = qs:block END
We put our text here.
Here we are, Doc.
END</syntaxhighlight>
 
Use the lead modifier to strip leading white space on each line.
 
<syntaxhighlight lang="langur">val .s = qs:lead:block END
We put our text here.
Here we are, Doc.
END</syntaxhighlight>
 
We can also use this with a regex literal. Note that this does not make the regex pattern "free-spacing." Use the x modifier for that.
 
<syntaxhighlight lang="langur">val .re = re:block END
a regex pattern here
Still here, Doc.
END</syntaxhighlight>
 
<syntaxhighlight lang="langur">val .re = re:x:block END
a free-spacing regex pattern here
Somewhere, Doc.
END</syntaxhighlight>
 
=={{header|Lingo}}==
Lingo has no heredoc syntax. Quotes inside string literals have to be escaped with "&QUOTE&".<br />
But you can define multi-line strings using the line continuation character "\":
 
<syntaxhighlight lang="lingo">str = "This is the first line.\
This is the second line.\
This "&QUOTE&"line"&QUOTE&" contains quotes."
 
put str</syntaxhighlight>
{{out}}
<pre>
This is the first line.
This is the second line.
This "line" contains quotes.
</pre>
 
For longer text it's more comfortable to put it into a named "field member" (=asset container) and load its text into a variable when needed:<syntaxhighlight lang="lingo">str = member("my long text").text
put str</syntaxhighlight>
 
=={{header|Lua}}==
Lua uses the [ [ to mark the start of a dochere block and ] ] to mark the end. It can be used directly or while assigning strings to a variable. An arbitrary but matching number of = may be placed between the brackets in both delimiters to allow ] ] to appear in the string.
<langsyntaxhighlight lang="lua">
print([[
This is a long paragraph of text
Line 662 ⟶ 1,272:
you set in this block.
]])
 
print([=[by using equals signs, ]] may be embedded.]=])
 
local msg = [[this is a message that spans
Line 670 ⟶ 1,282:
print(msg)
 
</syntaxhighlight>
</lang>
 
=={{header|M2000 Interpreter}}==
A block of { } can be used for code and for text. Editor in M2000 environment can color code/string on the fly, analyzing the first line, where the block start.
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
a$={This is the first line
This is the second line
End bracket position declare indentation fortext (except for first line)
}
Report a$ ' print all lines, without space at the left
}
CheckIt
</syntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Print["Mathematica
is an
interesing
Line 685 ⟶ 1,310:
when not
back\
s\\ashed!"];</langsyntaxhighlight>
{{out}}
<pre>Mathematica
Line 698 ⟶ 1,323:
when not
backs\ashed!</pre>
 
=={{header|MATLAB}}==
Matlab has no built-in heredoc syntax. The closest thing you can do is the following:
<syntaxhighlight lang="matlab">sprintf('%s\n',...
'line1 text',...
' line2 text',...
' line3 text',...
' line4 text')
 
sprintf('%s\n',...
'Usage: thingy [OPTIONS]',...
' -h Display this usage message',...
' -H hostname Hostname to connect to')</syntaxhighlight>
{{out}}
<pre>
'line1 text
line2 text
line3 text
line4 text
'
 
'Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
'</pre>
 
=={{header|NewLISP}}==
<syntaxhighlight lang="newlisp">; here-document.lsp
; oofoe 2012-01-19
; http://rosettacode.org/wiki/Here_document
 
(print (format [text]
Blast it %s! I'm a %s,
not a %s!
--- %s
[/text] "James" "magician" "doctor" "L. McCoy"))
 
(exit)</syntaxhighlight>
 
{{out}}
<pre>
Blast it James! I'm a magician,
not a doctor!
--- L. McCoy
</pre>
 
=={{header|Nim}}==
 
There are no heredocs, but triple-quoted-strings can be used:
<syntaxhighlight lang="nim">echo """Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
"""</syntaxhighlight>
 
=={{header|NMAKE.EXE}}==
<langsyntaxhighlight lang="nmake.exe">target0: dependent0
command0 <<
temporary, discarded inline file
Line 722 ⟶ 1,400:
named and preserved inline file
...
<<KEEP</langsyntaxhighlight>
 
=={{header|NewLISPOCaml}}==
<lang NewLISP>; here-document.lsp
; oofoe 2012-01-19
; http://rosettacode.org/wiki/Here_document
 
(print (format [text]
Blast it %s! I'm a %s,
not a %s!
--- %s
[/text] "James" "magician" "doctor" "L. McCoy"))
 
(exit)</lang>
 
<syntaxhighlight lang="ocaml">
print_string {whatever|
'hahah', `this`
<is>
\a\
"Heredoc" ${example}
in OCaml
|whatever}
;;
</syntaxhighlight>
{{out}}
<pre>
'hahah', `this`
Blast it James! I'm a magician,
<is>
not a doctor!
\a\
--- L. McCoy
"Heredoc" ${example}
in OCaml
</pre>
 
=={{header|Nim}}==
 
There are no heredocs, but triple-quoted-strings can be used:
<lang nim>echo """Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
"""</lang>
 
=={{header|OxygenBasic}}==
Line 767 ⟶ 1,438:
 
=={{header|Perl}}==
In Perl, there must not be a space between the "<<" and the token string. TheBy default, the ending token must always be the entire end line (i.e. no surrounding spaces) for it to be recognisedrecognized (but see exception below). Interpolation is allowed, like a double-quoted string:
 
<langsyntaxhighlight lang="perl">$address = <<END;
1, High Street,
$town_name,
West Midlands.
WM4 5HD.
END</langsyntaxhighlight>
 
If the token string contains spaces, the token after the "<<" must be quoted; otherwise the double-quotes is implicit:
<langsyntaxhighlight lang="perl">$pancake = <<"NO MORE INGREDIENTS";
egg
milk
flour
NO MORE INGREDIENTS</langsyntaxhighlight>
 
It is possible to make a here-document that behaves differently than a double-quoted string, by applying a different kind of quoting to the token. For example, if you use single quotes, then the here document will not support interpolation, like a normal single-quoted string:
 
<langsyntaxhighlight lang="perl">$x = <<'FOO';
No
$interpolation
here
FOO</langsyntaxhighlight>
 
Alternately, you can use backticks to cause the here document to be executed
and the result returned, just like a normal backtick operator:
 
<langsyntaxhighlight lang="perl">$output = <<`BAR`;
ls /home
BAR</langsyntaxhighlight>
 
Note that in the above examples, that a semicolon was left
Line 808 ⟶ 1,479:
nested expression:
 
<langsyntaxhighlight lang="perl">print(<<EOF . "lamb\n");
Mary had
a little
EOF</langsyntaxhighlight>
 
Since Perl 5.26, the here document can be indented by putting a '~' before the token. All spaces to the left of the ending token then become insignificant. This avoids having a disconcerting exdent in the middle of your code.
Although, technically speaking, it is also possible to break a statement
into two parts, with the here document in the middle
(i.e. continue the statement on the line after the terminating token).
However, please don't do this.
 
<lang perl>print(<<EOF
Mary had
a little
EOF
. "lamb\n");</lang>
 
=={{header|Perl 6}}==
Heredocs in Perl 6 use the <code>:to</code> modifier to a quoting operator,
such as <code>q</code> or <code>qq</code>.
The indentation of the end marker is removed from every line.
 
<lang perl6>my $color = 'green';
 
my $text = qq :to 'END';
some line
color: $color
another line
END</lang>
 
{{out}}
<pre>some line
color: green
another line
</pre>
 
(Note that the quotes around the "END" are not magic --- the marker is just a regular string; it's the `q` or `qq` that decides whether or not the heredoc interpolates.)
 
Multiple here docs may be stacked on top of each other.
 
{{works with|niecza}}
<lang perl6>my $contrived_example = 'Dylan';
sub freewheelin() {
print q :to 'QUOTE', '-- ', qq :to 'AUTHOR';
I'll let you be in my dream,
if I can be in yours.
QUOTE
Bob $contrived_example
AUTHOR
}
 
<syntaxhighlight lang="perl">sub flibbertigibbet {
freewheelin;</lang>
print <<~END;
 
Mary had
{{out}}
a little
<pre>
I'll let you be in my dream,lamb
if I can be in yours.END
}</syntaxhighlight>
-- Bob Dylan
</pre>
 
Both q and qq are specialised forms of [http://design.perl6.org/S02.html#Q_forms Q] which comes with many adverbs. Here a heredoc that only interpolates @-sigils.
 
<lang perl6>
my $s = Q :array :to 'EOH';
123 \n '"`
@a$bc
@a[]
EOH
 
dd $s; # OUTPUT«Str $var = "123 \\n '\"`\n \@a\$bc\n 1 2 3 4\n"»</lang>
 
=={{header|Phix}}==
Phix does not have here-docs. In Phix normal double quoted strings are single line and require escaping. Strings can also be entered by using triple doublequotes or single backticks to include linebreaks and avoid any backslash interpretation. If the literal begins with a newline, it is discarded and any immediately following leading underscores specify a (maximum) trimming that should be applied to all subsequent lines. Interpolation is left to printf and friends. Both """`""" and `"""` are valid. Examples:
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>string ts1 = """
<span style="color: #004080;">string</span> <span style="color: #000000;">ts1</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
this
this
"string"\thing"""
"string"\thing"""</span>
 
string ts2 = """this
<span style="color: #004080;">string</span> <span style="color: #000000;">ts2</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""this
"string"\thing"""
"string"\thing"""</span>
 
string ts3 = """
<span style="color: #004080;">string</span> <span style="color: #000000;">ts3</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
_____________this
_____________this
"string"\thing"""
"string"\thing"""</span>
 
string ts4 = `
<span style="color: #004080;">string</span> <span style="color: #000000;">ts4</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">`
this
this
"string"\thing`
"string"\thing`</span>
 
string ts5 = `this
<span style="color: #004080;">string</span> <span style="color: #000000;">ts5</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">`this
"string"\thing`
"string"\thing`</span>
 
string ts6 = `
<span style="color: #004080;">string</span> <span style="color: #000000;">ts6</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">`
_____________this
_____________this
"string"\thing`
"string"\thing`</span>
 
string ts7 = "this\n\"string\"\\thing"
<span style="color: #004080;">string</span> <span style="color: #000000;">ts7</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"this\n\"string\"\\thing"</span>
 
constant tests={ts1,ts2,ts3,ts4,ts5,ts6,ts7}
<span style="color: #008080;">constant</span> <span style="color: #000000;">tests</span><span style="color: #0000FF;">={</span><span style="color: #000000;">ts1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ts2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ts3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ts4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ts5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ts6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ts7</span><span style="color: #0000FF;">}</span>
for i=1 to length(tests) do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
for j=1 to length(tests) do
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
if tests[i]!=tests[j] then crash("error") end if
<span style="color: #008080;">if</span> <span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]!=</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span> <span style="color: #7060A8;">crash</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"error"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
printf(1,"""
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"""
____________Everything
____________Everything
(all %d tests)
works (all %d tests)
justworks
file.""",length(tests)) just
file."""</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">))</span>
printf(1,"""`""")
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"""`"""</span><span style="color: #0000FF;">)</span>
printf(1,`"""`)</lang>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">`"""`</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 935 ⟶ 1,553:
Interpolation is allowed, like a double-quoted string:
 
<langsyntaxhighlight lang="php">$address = <<<END
1, High Street,
$town_name,
West Midlands.
WM4 5HD.
END;</langsyntaxhighlight>
 
In PHP 5.3+, it is possible to make a here-document that does not interpolate
Line 946 ⟶ 1,564:
(like in Perl):
 
<langsyntaxhighlight lang="php">$x = <<<'FOO'
No
$interpolation
here
FOO;</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
We can use the '[http://software-lab.de/doc/refH.html#here here]' function:
 
<langsyntaxhighlight PicoLisplang="picolisp">(out "file.txt" # Write to "file.txt"
(prinl "### This is before the text ###")
(here "TEXT-END")
Line 963 ⟶ 1,581:
TEXT-END
 
(in "file.txt" (echo)) # Show "file.txt"</langsyntaxhighlight>
 
{{out}}
Line 978 ⟶ 1,596:
The Key is the At symbol @.
 
<syntaxhighlight lang="powershell">
<lang PowerShell>
$XMLdata=@"
<?xml version="1.0" encoding="utf-8"?>
Line 996 ⟶ 1,614:
</unattend>
"@
</syntaxhighlight>
</lang>
 
=={{header|Python}}==
Line 1,002 ⟶ 1,620:
It does however have [http://docs.python.org/py3k/tutorial/introduction.html#strings triple-quoted strings] which can be used similarly.
 
<langsyntaxhighlight lang="python">print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 1,013 ⟶ 1,631:
that this implies (breaks code indentation, no "interpolation"):
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket/base
 
Line 1,022 ⟶ 1,640:
EOF
)
</syntaxhighlight>
</lang>
{{out}}
<pre> Blah blah blah
Line 1,031 ⟶ 1,649:
that works well with code:
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang at-exp racket/base
 
Line 1,052 ⟶ 1,670:
(output @list|<<{And customizable delimiters
so @foo{} is just plain text}>>|)
</syntaxhighlight>
</lang>
{{out}}
<pre>Blah blah blah
Line 1,063 ⟶ 1,681:
And customizable delimiters
so @foo{} is just plain text</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
Heredocs in Raku use the <code>:to</code> modifier to a quoting operator,
such as <code>q</code> or <code>qq</code>.
The indentation of the end marker is removed from every line.
 
<syntaxhighlight lang="raku" line>my $color = 'green';
say qq :to 'END';
some line
color: $color
another line
END</syntaxhighlight>
{{out}}
<pre>some line
color: green
another line
</pre>
 
Note that the quotes around the "END" are not magic --- the marker is just a regular string; it's the `q` or `qq` that decides whether or not the heredoc interpolates.
 
Multiple here docs may be stacked on top of each other.
 
<syntaxhighlight lang="raku" line>my $contrived_example = 'Dylan';
sub freewheelin() {
print q :to 'QUOTE', '-- ', qq :to 'AUTHOR';
I'll let you be in my dream,
if I can be in yours.
QUOTE
Bob $contrived_example
AUTHOR
}
 
freewheelin;</syntaxhighlight>
 
{{out}}
<pre>
I'll let you be in my dream,
if I can be in yours.
-- Bob Dylan
</pre>
 
Both q and qq are specialised forms of [http://design.raku.org/S02.html#Q_forms Q] which comes with many adverbs. Here a heredoc that only interpolates @-sigils.
 
<syntaxhighlight lang="raku" line>my @a = <1 2 3 4>;
say Q :array :to 'EOH';
123 \n '"`
@a$bc
@a[]
EOH</syntaxhighlight>
 
{{out}}
<pre>
123 \n '"`
@a$bc
1 2 3 4</pre>
 
=={{header|Raven}}==
As a list:
<langsyntaxhighlight Ravenlang="raven">'Buffy the Vampire Slayer' as sender
'Spike' as recipient
 
Line 1,077 ⟶ 1,751:
"%(sender)s
] "\n" join print
</syntaxhighlight>
</lang>
Using group to place the data on the stack:
<langsyntaxhighlight Ravenlang="raven">'Buffy the Vampire Slayer' as sender
'Spike' as recipient
 
Line 1,090 ⟶ 1,764:
%(sender)s\n"
list "\n" join print
</syntaxhighlight>
</lang>
{{out}}
<pre>Dear Spike,
Line 1,098 ⟶ 1,772:
Not Quite Love,
Buffy the Vampire Slayer</pre>
 
=={{header|Retro}}==
Retro does not have a builtin '''here document'''.
It does support multiline strings:
 
<lang Retro>"This is
a multi-line string
with indention
and such"</lang>
 
If you need an actual '''heredoc''' function, the following should suffice:
 
<lang Retro>{{
: getDelimiter ( "-$ )
getToken keepString cr ;
: prepare ( -$ )
remapping off "" tempString ;
: readLine ( "-$ )
10 accept tib ;
: append? ( $$-$$f )
[ over ] dip compare [ 0 ] [ tib ^strings'append 10 ^strings'appendChar -1 ] if ;
---reveal---
: heredoc ( "-$ )
heap [ remapping [ getDelimiter prepare [ readLine append? ] while nip ] preserve ] preserve ;
}}
 
heredoc [END]
1 2 3
4 5 6
7 8 9
[END]</lang>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates a method to use "here" documents in REXX. */
parse arg doc . /*"here" name is case sensitive. */
 
Line 1,191 ⟶ 1,834:
└─────────┘
◄◄.
────────────────────────────────────end of "here" docs──────────────────*/</langsyntaxhighlight>
{{out}} when using the input of: <tt> rs-232 </tt>
<pre>
Line 1,242 ⟶ 1,885:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
text ="
<<'FOO'
Line 1,254 ⟶ 1,897:
to come to the aid of their country."
see text + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,273 ⟶ 1,916:
Interpolation is allowed, like a double-quoted string:
 
<langsyntaxhighlight lang="ruby">address = <<END
1, High Street,
#{town_name},
West Midlands.
WM4 5HD.
END</langsyntaxhighlight>
 
If the token string contains spaces, the token after the "<<" must be quoted; otherwise the double-quotes is implicit:
 
<langsyntaxhighlight lang="ruby">pancake = <<"NO MORE INGREDIENTS"
egg
milk
flour
NO MORE INGREDIENTS</langsyntaxhighlight>
 
It is possible to make a here-document that behaves differently than a double-quoted string, by applying a different kind of quoting to the token.
For example, if you use single quotes, then the here document will not support interpolation, like a normal single-quoted string:
 
<langsyntaxhighlight lang="ruby">x = <<'FOO'
No
#{interpolation}
here
FOO</langsyntaxhighlight>
 
Alternately, you can use backticks to cause the here document to be executed
and the result returned, just like a normal backtick operator:
 
<langsyntaxhighlight lang="ruby">output = <<`BAR`
ls /home
BAR</langsyntaxhighlight>
 
The here document does not start immediately at the "<<END" token -- it starts on the next line.
Line 1,309 ⟶ 1,952:
To further illustrate this fact, we can use the "<<END" inside a complex, nested expression:
 
<langsyntaxhighlight lang="ruby">puts <<EOF + "lamb"
Mary had
a little
EOF</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">text$ ="
<<'FOO'
Now
Line 1,325 ⟶ 1,968:
good mem
to come to the aid of their country."
print text$</langsyntaxhighlight>
{{out}}
<pre><<'FOO'
Line 1,339 ⟶ 1,982:
=={{header|Rust}}==
 
Similar to [[#C++|C++]], Rust offers raw strings. In a manner resembling [[#Lua|Lua]]'s delimiters, an arbitrary but matching number of # on both ends may be used to allow inclusion of # into the string:
 
<langsyntaxhighlight lang="rust">let x = r#"
This is a "raw string literal," roughly equivalent to a heredoc.
"#;</lang>
 
let y = r##"
This string contains a #.
"##;
</syntaxhighlight>
 
=={{header|Scala}}==
Line 1,351 ⟶ 1,999:
Triple quotes (""") marks the beginning and end.
Specially handy when using escape sequences in e.g. regular expressions.
{{libheader|Scala}}<langsyntaxhighlight Scalalang="scala">object temp {
val MemoriesOfHolland=
"""Thinking of Holland
Line 1,377 ⟶ 2,025:
|with its lapping disasters
|is feared and hearkened.""".stripMargin
}</langsyntaxhighlight>
All control codes are transparent e.g. new lines.
In order for a neat code each lines has as prefix spaces and a | symbol
which will be removed by the stripMargin function.
 
=={{header|sed}}==
<syntaxhighlight lang="sed">c\
The commands 'a', 'c', and 'i' can be followed\
by multi-line text. Each line break in the text\
is preceded by a backslash.</syntaxhighlight>
{{out}}
<pre>
$ echo | sed -f heredoc.sed
The commands 'a', 'c', and 'i' can be followed
by multi-line text. Each line break in the text
is preceded by a backslash.
</pre>
 
=={{header|SenseTalk}}==
SenseTalk has "block quotes" for large blocks of text, enclosed between <nowiki>"{{"</nowiki> (at the end of a line) and "}}" (at the beginning of a line). A tag can also be used after the <nowiki>"{{"</nowiki> and before the "}}" which allows for nesting of blocks, such as for a block of code containing other block quotes.
 
<syntaxhighlight lang="sensetalk">
set script to {{SCRIPT
put "Script demonstrating block quotes"
 
set text to {{
"I wish it need not have happened in my time," said Frodo.
"So do I," said Gandalf, "and so do all who live to see such times. But that is not for them to decide. All we have to decide is what to do with the time that is given us."
}}
 
put the number of occurrences of "time" in text --> 3
 
SCRIPT}}
 
do script
 
</syntaxhighlight>
 
=={{header|SequenceL}}==
<syntaxhighlight lang="sequencel">main :=
"In SequenceL
strings are
multiline
by default.
'All' non-\"
characters are
valid for inclusion
in a string.";</syntaxhighlight>
 
{{out}}
<pre>
"In SequenceL
strings are
multiline
by default.
'All' non-"
characters are
valid for inclusion
in a string."
</pre>
 
=={{header|Sidef}}==
Line 1,386 ⟶ 2,090:
When the token string is double-quoted ("") or not quoted,
the content will be interpolated like a double-quoted string:
<langsyntaxhighlight lang="ruby">var text = <<"EOF";
a = #{1+2}
b = #{3+4}
EOF</langsyntaxhighlight>
 
If single quotes are used, then the here document will not support interpolation, like a normal single-quoted string:
<langsyntaxhighlight lang="ruby">var x = <<'FOO';
No
#{interpolation}
here
FOO</langsyntaxhighlight>
The here document does not start immediately at the "<<END" token -- it starts on the next line. The "<<END" is actually an expression, whose value will be substituted by the contents of the here document.
To further illustrate this fact, we can use the "<<END" inside a complex, nested expression:
<langsyntaxhighlight lang="ruby">say (<<EOF + "lamb");
Mary had
a little
EOF</langsyntaxhighlight>
which is equivalent with:
<langsyntaxhighlight lang="ruby">say (<<EOF
Mary had
a little
EOF
+ "lamb");</langsyntaxhighlight>
 
=={{header|SQL PL}}==
{{works with|Db2 LUW}}
With SQL only from command line. The single quote string is opened along the three lines:
<syntaxhighlight lang="bash">
db2 "select 'This is the first line.
This is the second line.
This is the third line.' from sysibm.sysdummy1"
</syntaxhighlight>
Output:
<pre>
1
------------------------------------------------------------------------
This is the first line.
This is the second line.
This is the third line.
 
1 record(s) selected.
</pre>
With SQL only from script with concat function (one row):
<syntaxhighlight lang="sql pl">
select 'This is the first line.' || chr(10) ||
'This is the second line.' || chr(10) ||
'This is the third line.' from sysibm.sysdummy1;
</syntaxhighlight>
Output:
<pre>
1
------------------------------------------------------------------------
This is the first line.
This is the second line.
This is the third line.
 
1 record(s) selected.
</pre>
With SQL only from script with union operator (three rows):
<syntaxhighlight lang="sql pl">
select 'This is the first line.' from sysibm.sysdummy1
union
select 'This is the second line.' from sysibm.sysdummy1
union
select 'This is the third line.' from sysibm.sysdummy1;
</syntaxhighlight>
Output:
<pre>
1
------------------------
This is the first line.
This is the second line.
This is the third line.
 
3 record(s) selected.
</pre>
{{works with|Db2 LUW}} version 9.7 or higher.
With SQL PL:
<syntaxhighlight lang="sql pl">
SET serveroutput ON
CALL DBMS_OUTPUT.PUT_LINE('This is the first line.' || chr(10) ||
'This is the second line.' || chr(10) ||
'This is the third line.');
</syntaxhighlight>
Output:
<pre>
 
Return Status = 0
 
This is the first line.
This is the second line.
This is the third line.
</pre>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">set hereDocExample {
In Tcl, the {curly brace} notation is strictly a here-document style notation
as it permits arbitrary content inside it *except* for an unbalanced brace.
Line 1,423 ⟶ 2,197:
plus all whitespace at the start of the next line
to be compressed to a single space.
}</langsyntaxhighlight>
 
If substitution is desired within the document, it should either be written
Line 1,443 ⟶ 2,217:
to the resulting script which are interpreted by txr.
 
<langsyntaxhighlight lang="txr">#!/usr/bin/txr -f
@(maybe)
@(bind USER "Unknown User")
Line 1,455 ⟶ 2,229:
 
The Computer
@(end)</langsyntaxhighlight>
 
Test runs
Line 1,496 ⟶ 2,270:
{{works with|Bourne Shell}}
 
<langsyntaxhighlight lang="bash">#!/bin/sh
cat << ANARBITRARYTOKEN
The river was deep but I swam it, Janet.
Line 1,503 ⟶ 2,277:
I've one thing to say and that's ...
Dammit. Janet, I love you.
ANARBITRARYTOKEN</langsyntaxhighlight>
 
<langsyntaxhighlight lang="bash">cat << EOF
Here documents do parameter and command substitution:
* Your HOME is $HOME
* 2 + 2 is `expr 2 + 2`
* Backslash quotes a literal \$, \` or \\
EOF</langsyntaxhighlight>
 
<langsyntaxhighlight lang="bash">if true; then
cat <<- EOF
The <<- variant deletes any tabs from start of each line.
EOF
fi</langsyntaxhighlight>
 
<langsyntaxhighlight lang="bash">cat << 'TOKEN'
If TOKEN has any quoted characters (like 'TOKEN', "TOKEN" or \TOKEN),
then all $ ` \ in the here document are literal characters.
 
$PATH \$PATH `shutdown now`
TOKEN</langsyntaxhighlight>
<syntaxhighlight lang="bash">echo '
In any unix shell, you specify a text block and can use all whitespace like
(spaces) & (tab) in it, by using single quotes.
As mentioned above, a Unix "here document" is a type of redirection.
In a literal Bash here document, the starting token must be
quoted, but the end token must not, so they are not the same, which does not
conform to the task definition.
'
</syntaxhighlight>
 
==={{header|C Shell}}===
<langsyntaxhighlight lang="csh">#!/bin/csh -f
cat << ANARBITRARYTOKEN
* Your HOME is $HOME
Line 1,534 ⟶ 2,317:
cat << 'ANARBITRARYTOKEN'
$PATH \$PATH `shutdown now`
'ANARBITRARYTOKEN'</langsyntaxhighlight>
 
=={{header|Ursala}}==
<langsyntaxhighlight Ursalalang="ursala">hd =
 
-[
Line 1,586 ⟶ 2,369:
the periods like this -[.. ~&]-. This one is a second order function
that needs to be applied to another function in order to get a
first order function such as the previous three examples.]-</langsyntaxhighlight>
 
{{omit from|8086 Assembly}}
{{omit from|80386 Assembly}}
{{omit from|BASIC}}
{{omit from|C|No such thing}}
{{omit from|GUISS}}
{{omit from|Icon}}{{omit from|Unicon}}
{{omit from|Java|Unsupported}}
{{omit from|JavaScript}}
{{omit from|LabVIEW|Not a text-based language}}
{{omit from|Locomotive Basic|Does not support here documents}}
{{omit from|Lotus 123 Macro Scripting}}
{{omit from|NetRexx}}
{{omit from|Openscad}}
{{omit from|Z80 Assembly}}
{{omit from|ZX Spectrum Basic|Does not support here documents}}
 
 
=={{header|VBScript}}==
Line 1,610 ⟶ 2,376:
 
It will prompt you to select a Txt-based file and do its best to create VBScript code that will recreate that Txt-based file!
<syntaxhighlight lang="vbscript">
<lang VBScript>
'Purpose: Converts TXT files into VBS code with a function that returns a text string with the contents of the TXT file
' The TXT file can even be another VBS file.
 
'History:
' 1.0 8may2009 Initial release
'
'
Line 1,632 ⟶ 2,398:
If intResult = 0 Then
WshShell.Popup "No file selected.", 2, " ", 64
Wscript.Quit
Else
Line 1,643 ⟶ 2,409:
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists(strFileNameOUT) then 'does the file EXIST?
' WScript.Echo "found"
OVRWT=MSGBOX(strFileNameOUT & " exists already"&vbCRLF&"Overwrite?",vbYesNoCancel,"Overwrite?")
if OVRWT = 6 then
'proceed
objFSO.DeleteFile(strFileNameOUT)
else
WshShell.Popup "Exiting as requested.", 1, " ", 64
Wscript.Quit
End If
Else
' WScript.Echo "not found" 'strFileNameOUT does NOT exists already
END if
 
Line 1,674 ⟶ 2,440:
'Add objTXTFile.writeline ("
strOldText = VBCRLF
strNewText = """) &vbCrLf"&VBCRLF&" strText=strText& ("""
strText = Replace(strText, strOldText, strNewText)
'Converting done
Line 1,686 ⟶ 2,452:
objFile.WriteLine vbCrLf
objFile.WriteLine "Function "&strBaseName&"()"
objFile.WriteLine " 'returns a string containing the contents of the file called "&strFileName
objFile.WriteLine " Dim strText"
objFile.WriteLine " strText= ("""&strText&""") &vbCrLf"
objFile.WriteLine " "&strBaseName&"=strText"
objFile.WriteLine "End Function"
objFile.Close
 
WshShell.Popup "created " & strFileNameOUT, 3, "Completed", 64
</syntaxhighlight>
</lang>
 
=={{header|V (Vlang)}}==
Vlang does not have here documents. Multiline string literals serve this purpose.
 
<syntaxhighlight lang="go">fn main() {
m := ' leading spaces
and blank lines'
 
println(m)
}</syntaxhighlight>
 
=={{header|Wren}}==
Wren does not have heredocs but (from v0.4.0) does have raw strings.
 
A raw string is any text delimited by triple quotes, """, and is interpreted literally i.e. any control codes and/or interpolations are not processed as such.
 
If a triple quote appears on its own line then any trailing whitespace on that line is ignored.
 
Borrowing the Ada example (appropriately adjusted) for an illustration of a raw string.
<syntaxhighlight lang="wren">var a = 42
var b = """
This is a 'raw' string with the following properties:
- indention is preserved,
- an escape sequence such as a quotation mark "\\" is interpreted literally, and
- interpolation such as %(a) is also interpreted literally.
`Have fun!`
"""
System.print(b)</syntaxhighlight>
 
{{out}}
<pre>
This is a 'raw' string with the following properties:
- indention is preserved,
- an escape sequence such as a quotation mark "\\" is interpreted literally, and
- interpolation such as %(b) is also interpreted literally.
`Have fun!`
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">code Text=12;
Text(0, " ^"Heredocs^" are pretty much automatic. Multiple lines and
whitespace, such as indentations, are output exactly as written. Quote
marks (^") and any carets (^^) within the string must be escaped.")</langsyntaxhighlight>
 
=={{header|XSLT}}==
Line 1,706 ⟶ 2,510:
Being a dialect of XML, XSLT inherits [http://www.w3.org/TR/REC-xml/#sec-cdata-sect CDATA sections]. Not quite heredocs, these are more like raw triple quotes in Python (<code>r"""…"""</code>) or Scala (<code>"""…"""</code>) in that anything except the end delimiter is treated literally.
 
<langsyntaxhighlight lang="xml"><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="text"/>
Line 1,722 ⟶ 2,526:
now:
 
]]>]]<![CDATA[>
 
Newlines and spacing are retained as well, as long as they're evaluated in a
Line 1,730 ⟶ 2,534:
]]>
</xsl:template>
</xsl:stylesheet></langsyntaxhighlight>
 
Output from xsltproc (input is ignored):
Line 1,747 ⟶ 2,551:
now:
 
]]>
 
Newlines and spacing are retained as well, as long as they're evaluated in a
Line 1,755 ⟶ 2,559:
 
</pre>
 
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">
text1$ = "Esta es la primera linea.
Esta es la segunda linea.
Esta \"linea\" contiene comillas.\n"
 
text2$ = "Blast it James! I'm a magician,
not a doctor!
--- L. McCoy\n"
 
 
print text1$
print text2$
end
</syntaxhighlight>
{{out}}
<pre>
Esta es la primera linea.
Esta es la segunda linea.
Esta "linea" contiene comillas.
 
Blast it James! I'm a magician,
not a doctor!
--- L. McCoy
</pre>
 
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">x:=
#<<<
"#<<< starts a block of lines that are concatenated verbatim
Line 1,765 ⟶ 2,597:
Note that is isn't a string, but arbitrary source " + 1 + 23;
#<<<
x.println();</langsyntaxhighlight>
{{out}}
<pre>
Line 1,774 ⟶ 2,606:
Note that is isn't a string, but arbitrary source 123
</pre>
 
{{omit from|8086 Assembly}}
{{omit from|80386 Assembly}}
{{omit from|BASIC}}
{{omit from|BBC BASIC}}
{{omit from|C|C's "multi-line strings" don't fulfill the requirements of this task}}
{{omit from|Déjà Vu}}
{{omit from|Gambas}}
{{omit from|GUISS}}
{{omit from|GW-BASIC}}
{{omit from|Icon}}
{{omit from|Java|Unsupported}}
{{omit from|JavaScript}}
{{omit from|LabVIEW|Not a text-based language}}
{{omit from|Locomotive Basic|Does not support here documents}}
{{omit from|Lotus 123 Macro Scripting}}
{{omit from|MATLAB|MATLAB has no multiline string literal functionality}}
{{omit from|NetRexx}}
{{omit from|Openscad}}
{{omit from|Pascal}}
{{omit from|Processing|Unsupported}}
{{omit from|Unicon}}
{{omit from|VBA|VBA can't create a console application}}
{{omit from|Z80 Assembly}}
{{omit from|ZX Spectrum Basic|Does not support here documents}}
[[Category: Syntax elements]]
890

edits