HERE documents

HERE documents

Introduction

If you’re tempted to write multi-line output with multiple print()
statements, because that’s what you’re used to in some other language,
consider using a HERE-document instead.

Inspired by the here-documents in the Unix command line shells, Perl
HERE-documents provide a convenient way to handle the quoting of
multi-line values.

So you can replace this:

with this:

The EOT in this example is an arbitrary string that you provide to
indicate the start and end of the text being quoted. The terminating string
must appear on a line by itself.

Quoting conventions.

The usual Perl quoting conventions apply, so if you want to interpolate
variables in a here-document, use double quotes around your chosen
terminating string:

Note that whilst you can quote your terminator with " or ', you
cannot use the equivalent qq() and q() operators. So this
code is invalid:

The terminating string

Naturally, all of the text you supply to a here-document is quoted by the
starting and ending strings. This means that any indentation you provide
becomes part of the text that is used. In this example, each line of the
output will contain four leading spaces.

The terminating string must appear on a line by itself, and it must
have no whitespace before or after it. In this example, the terminating
string EOT is preceeded by four spaces, so Perl will not find it:

Assignment

The here-document mechanism is just a generalized means of quoting text,
so you can just as easily use it in an assignment:

And don’t let the samples you’ve seen so far stop from considering the
full range of possibilities. The terminating tag doesn’t have to appear
at the end of a statement.

Here is an example from CPAN.pm that conditionally assigns some text to
$msg.

And this example from Module::Build::PPMMaker uses a here-document to
construct the format string for sprintf():

See Also

Scroll to Top