Perl Multiline Strings: Choosing Between Quotes, q/qq and Heredocs

How Perl multiline strings work with quotes, q/qq and heredocs: what each form changes, interpolation risks, indented heredocs, and copy-paste pitfalls.

Turning a block of text into a Perl multiline string looks simple, but the quoting form decides what ends up in the variable. Perl may expand variables, interpret backslash escapes, or keep every character exactly as typed. This review covers the main options, what each one changes, and when the text should stay outside the source code.

Which form suits which job

For most multiline text in code, a heredoc is the most readable choice. The text sits on its own lines, and quotes inside it need no escaping. Use the single-quoted form (<<'EOT') when the content must arrive unchanged. Use the double-quoted form (<<"EOT") only when you deliberately want variables filled in. On Perl 5.26 or later, the indented form (<<~EOT) keeps nested code tidy.

The decisive tradeoff is convenience versus silent change. Interpolation is handy, but any dollar sign or at sign in the text can be expanded without warning unless strict and warnings catch it. Plain text kept in a separate file, or in a DATA section, is preferable in several cases: the text is long, non-programmers edit it, it gets translated, or it must stay byte-exact.

What the transformation actually changes

A Perl string literal is not a visual effect like mirrored or restyled lettering. Nothing about how the text looks is altered; the only question is which characters are stored in the scalar. Two separate mechanisms are involved. Escaping is how the source must be written so the parser reads it correctly, such as a backslash before a quote. Interpolation is whether variables and escape sequences like \n are expanded into other characters.

Form | Interpolates variables | Backslash handling | Main risk
'...' | No | Only \ and ' are special | Apostrophes in the text must be escaped
"..." | Yes | Full escape set (\n, \t, $, @ and others) | $ and @ in the text are expanded
q{...} | No | Only \ and an escaped delimiter are special | Unbalanced delimiter characters in the text
qq{...} | Yes | Full escape set | Same as double quotes
<<'EOT' | No | None; backslashes are kept exactly as typed | Terminator line must match exactly
<<"EOT" or bare <<EOT | Yes | Full escape set | Same as double quotes
<<~EOT (any quoting) | Follows its quoting style | Follows its quoting style | Requires Perl 5.26+; inconsistent indentation is a fatal error

Quotes and quote-like operators

Ordinary quotes can span several lines, and the literal line breaks become part of the string:

my $sql = 'SELECT id, name
FROM users
WHERE active = 1';

This works for short text. However, the first line hugs the assignment, and any indentation added for neatness becomes part of the string. The q{} and qq{} operators let you pick a delimiter that does not appear in the text. Inside qq, double quotes need no escaping, but a dollar sign still does:

my $name = 'report';
my $msg  = qq{Generated "$name"
Total: \$0.00
};

Here $name becomes report, and $0.00 becomes a literal $0.00. With bracket delimiters, nested balanced pairs inside the text are allowed. An unmatched closing brace would end the string early.

Heredocs

A heredoc starts with a marker such as <<"EOT" and takes every following line until a line containing only the terminator. The statement's semicolon belongs after the marker on the opening line, not after the terminator.

my $user = 'Ada';

print <<"EOT";
Hello, $user.
Your balance is \$12.
EOT

print <<'EOT';
Hello, $user.
Backslashes stay as typed: C:\temp\new
EOT

By Perl's documented rules, this prints:

Hello, Ada.
Your balance is $12.
Hello, $user.
Backslashes stay as typed: C:\temp\new

In the double-quoted heredoc, the variable is filled in and the escaped dollar sign is unescaped. The single-quoted heredoc is the most literal construct Perl offers. Even a double backslash stays as two characters, unlike in a single-quoted string. Every heredoc ends with a newline after its last line; apply chomp if you do not want it.

Indented heredocs

Since Perl 5.26, adding a tilde lets the body follow the code's indentation:

sub usage {
    return <<~'EOT';
        Usage: tool [options]
          -v  verbose output
        EOT
}

Perl removes from each line the leading whitespace that matches the terminator's indentation. Here the result begins with Usage at the start of the line, and the option line keeps its two extra spaces. Whitespace is matched character for character, so mixing tabs and spaces can produce a fatal indentation error. A line indented less than the terminator also triggers it.

Alternatives to a single literal

  • join("\n", @lines) builds the string from a list, which suits text assembled from data.
  • Concatenation with the . operator works, but it grows noisy beyond a few lines.
  • A DATA section keeps a block of plain text at the end of the script, readable through the DATA filehandle.
  • A separate text or template file keeps content fully independent of Perl's quoting rules.

Will the string survive copying and sharing?

The stored text is ordinary characters, so a Perl string has none of the reading-order or substitution problems of styled Unicode text. The fragile part is the source code that produces it. Common hazards when snippets are pasted between editors, documents and chat tools:

  • Terminator lines: in a classic heredoc, the terminator must stand alone at the start of its line. Added indentation or trailing spaces stop Perl from finding the end of the string.
  • Tabs and spaces: editors that convert tabs can break the indentation matching that <<~ depends on.
  • Curly quotes: some word processors and messaging tools replace straight quotes with typographic ones. Perl does not accept these as string delimiters.
  • Line endings: if a file picks up Windows line endings, check whether carriage returns have ended up inside the string.
  • Encoding: non-ASCII text in a literal is only treated as characters, not raw bytes, when the file declares use utf8 and is actually saved as UTF-8.

Escaping also affects search and editing. Text in a single-quoted heredoc appears in the source exactly as it will be stored, so a plain-text search for a phrase finds it. Escaped forms such as " or $, and text split across concatenations, break exact-phrase searches and make edits riskier.

When the audience is not reading code, share a plain-text equivalent of the final output rather than the literal. Reviewers, translators and people using screen readers otherwise have to mentally strip delimiters and escape sequences. No assistive technology was tested for this review.

Evidence and gaps

Everything above follows Perl's documented quoting rules; no measurements, benchmarks or tool-specific tests were available. The example outputs show expected behavior, not recorded runs, so confirm them on your own Perl version, especially anything using <<~. No particular text-to-Perl-string converter was evaluated. How any such tool handles dollar signs, at signs, backslashes or non-ASCII input remains unverified and should be checked against your own sample text before relying on it.