<<
), 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.