display | more...
Here document is a special syntax feature in scripting languages to tell the interpreter to treat a certain portion of the script text as a multi-line document or string literal. In essence, it is a fancy way of saying "multi-line string" (and by line we mean here lines of source code).

A here document is created by using the following syntax: start with the here document quote operator (In Unix shells and Perl, this is << ) followed by an end delimiter (this can be almost anything, so just pick anything that is unlikely to appear in the text). The interpreter will then treat the following lines as one string, up to (but not including) the first line containing ONLY your end delimiter (it shall not even contain a blank before it).

Examples

$a = <<END
Hello
world
END
print $a;

will result in exactly the same as had you written

$a = "Hello\nworld\n";
print $a;

That is, it will print this:

Hello
world

By default, Perl here documents are double-quote interpolated. You can explicitely set the quoting behaviour by putting the appropriate quote characters around the end delimiter (in the declaration):

print <<'END';
Use this for tabs: \t
Use this for newline: \n
END

will print:

Use this for tabs: \t
Use this for newline: \n
Or, you may even use this with backquote interpolation to create multi-line inline shell script in Perl:
print <<`END`;
ls spam/
ls eggs/
END

This string will contain the contents of the directories spam and eggs, provided that they exist, one after another.

Another popular use for here documents is to allow copy-pasteing static HTML code into your Perl scripts.

Obfuscation

To make things more complicated, you are allowed to define more than one here document on the same line. In this case, parsing the next here document will continue where the previous one left off, i.e.:

print <<END1, <<END2;
Hello
END1
world
END2

will print

Hello
world

just as if you would have written:

print "Hello\n", "world\n";

Log in or register to write something here or to contact authors.