next up previous contents
Next: Printing to a String Up: Basic I/O Previous: Changing the Destination of   Contents

Printing Blocks of Text

When you need to print several lines of text, it becomes tiresome to either call the print function for each individual line or to insert \n characters after every line, and your program may become disorganized due to the presence of long character strings. This problem arises when, for example, you are generating form letters or mutltiple pages of html text from inside a perl program, or you want your perl program to print out a detailed help message. To solve this problem, perl borrows a concept from shell scripts known as a ``here-is'' document. You inform perl that the text that follows should be treated as a single block by using two less-than signs (<<), immediately followed by an arbitrary string of your choice. Since this is actually a perl statement, it must be terminated by a semi-colon. Then you can provide perl with as much text as you want, spread out across as many lines as necessary, signalling to perl that you're done by providing a line with nothing but the string you chose on the first line, starting in the first column, and with no semicolon. While there is no need to do so, many perl programmers use the string EOF (end of file) as a delimiter for here-is documents.

This construction is most often used with the print statement, but you can also use it to set variables equal to blocks of text (although it won't work in the debugger). Thus, to put three lines of text into the variable $threelines, you could use the following code:

        $threelines = <<EOF;
Here is the first line
Now here's the second
Finally the third
EOF

Since variable interpolation takes place inside of here-is documents, it can be used to generate documents which are basically similar except for a few strings. To illustrate, suppose we wish to produce a memo to a variety of people informing them of their account balances. Further suppose that we have a hash called %balances, with keys for each of the people we wish to send the memo. We could generate the memos with code like the following:

$fh = new IO::File;
foreach $p (keys(%balances)){
    $fh->open("$p.memo","w");
    print $fh <<EOF;
To: $p
Re: Your Account Balance

This memo is to inform you that your account balance is currently
$balances{$p}.  Please send your payment as soon as possible.

Thank you.
EOF
}

The quoting operators (Section 3.2) also provide a convenient solution to problems such as this. The main difference is that, if you start the block of text on the line after the quoting operator, an empty line will appear at the start of the block, whereas the here-is construction requires that the block of text begins on the line following its invocation.


next up previous contents
Next: Printing to a String Up: Basic I/O Previous: Changing the Destination of   Contents
Phil Spector 2002-10-18