Use Perl here documents to print multiple lines of output

Summary: How to use Perl here documents, i.e., the Perl heredoc syntax.

Perl offers a convenient way of printing multiple lines of output through an interesting feature known as a "Perl here document". A here document, or heredoc, lets you easily store multiple lines of text in a Perl variable.

A multiline Perl here document works like this:

  1. The first line of your command will include the two characters << followed by a "special" identifier string, followed by a semi-colon. (For my example I will use the identifier string FOO. More on this shortly.)
  2. Next, just enter all of the lines of output that you want to print.
  3. When you are ready to terminate the output, put your special identifier string on a line by itself to end the output.

A Perl here document example

Confused? Probably. Here's an example of how to use this. Imagine you wanted to print a few lines from the Gettysburg address from inside of a Perl program:

print <<FOO;
Four score and seven years ago
our fathers set onto this continent
(keep going here ...)
FOO

If you put this in a Perl program, and then run the program, this will print the lines in between "print <<FOO;" and "FOO", so you will see this output:

Four score and seven years ago
our fathers set onto this continent
(keep going here ...)

I don't know the history, so I can't tell you why they're called "here" documents, but I can tell you that it makes it easy to print multiple lines of output from a Perl program.

Perl here documents (heredoc) - Summary

I hope these Perl heredoc examples have been helpful. As you can see, the Perl heredoc syntax lets you easily store multiple lines of text in a Perl variable, and when you think about the alternative syntax required to achieve something like this, you realize how incredibly useful the Perl here document syntax is.