Siaris

Using Here-docs
22 Feb 01 - http://www.siaris.net/index.cgi/Programming/LanguageBits/Perl/20010222.rdoc

Perl has several quoting mechanisms, but the here-doc is the most convenient for quoting multiline strings. You may be familiar with such constructs from shell programming. The basic syntax is to follow doubled left-angle brackets with a terminator string and a semi-colon, all lines after that up to the terminator are quoted.

    my $string = <<EOS;
    this is part of the string
    and so is this
    EOS

    # now we are out of the quoted string

There are a few points to be aware of: By default, such a string is considered to be double quoted (so variable interpolation works as expected); and the final terminator should be flush with the left margin and by itself on a line (no trailing spaces or tabs or anything else). Thus, even though all the code is indented here, you are to assume that it is flush left. To achieve a single version you surround your initial terminator specifier with single quotes:

    my $string = <<'EOS';
        this is a
        single quoted
        here-doc
    EOS

Note, all indentation and spacing is preserved, this is simple a multiline string. Besides single or double quotes, you can also use backtics to have your multiline string executed as shell commands:

    print <<`SHELL`;
    echo Hello
    ls -l
    SHELL

One good reason to use here-docs is to avoid multiple print statements, say when printing several lines of HTML:

    print "<html>\n";
    print "<head><title>Whatever</title></head>\n";
    print "<body>\n";
    # and more of the same

    print <<HTML;
    <html>
    <head><title>Whatever</title></head>
    <body>
    HTML

Now we’ve avoided explicitly using quotes and newlines and our output is contained in a nice little chunk.

Here-docs can also be stacked, either for direct printing (not so useful perhaps) or when providing multiline quoted strings as arguments to some function:

    $two = "this is the second\n";
    print <<FIRST, $two, <<THIRD;
    Here is the
    first string
    FIRST
    And here is
    the third
    THIRD

    foo(<<FIRST, $two, <<THIRD);
    Here is the
    first argument
    FIRST
    And here is
    the third
    THIRD

    sub foo {
        my($first, $second, $third) = @_;
        print "$first$second$third";
    }

The perldata manpage documents here-doc syntax along with a method a allowing for indentation. The faqs (perlfaq4 in particular) also shows several methods of arranging various indentation and block-like formatting of here-docs.