Using "here" documents in Perl to print multiple lines of output

By Alvin J. Alexander, devdaily.com

Using "here" documents in Perl

Perl offers a convenient way of printing multiple lines of output through an interesting feature known as a "here" document. A 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.

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!


devdaily logo