Date: 2010sep12
Updated: 2016mar4
Language: PHP, perl, C/C++, javaScript, Java, Python
Keywords: heredoc, inline text, multiline
Q. What is the syntax for PHP, perl, C/C++, javaScript, Java and Python heredocs?
The syntax is close but different enough to drive me crazy.
A.
In PHP:
my $mydoc = <<<EOT
line one
line two
$variables_work_here
line three
EOT;
In perl:
my $mydoc = <<EOT;
line one
line two
$variables_work_here
line three
EOT
In C/C++:
There is no exact equivalent but you can take advantage of a trick:
C/C++ will concatenate adjacent strings.
char *mydoc =
"line one\n"
"line two\n"
"line three\n";
Use sprintf() to put variables into a string.
In javaScript:
Again, there is no heredoc. But you can use a backslash for more
compact multiline strings:
var mydoc =
"line one\
line two\
line three";
It would be great for JSON if javaScript supported a heredoc.
In Java:
On Android use a string resource.
Regular Java doesn't have an official way but this works OK:
String mydoc =
"line one\n" +
"line two\n" +
"line three\n";
In Python:
Use triple double quotes:
String mydoc = """
line one
line two
I said "hello"
last line
"""