Indenting Here Documents
Problem
When using the multiline quoting mechanism called a here document, the text must be flush against the margin, which looks out of place in the code. You would like to indent the here document text in the code, but not have the indentation appear in the final string value.
Solution
Use a s///
operator to strip out leading
whitespace.
# all in one
($var = <<HERE_TARGET) =~ s/^\s+//gm;
your text
goes here
HERE_TARGET
# or with two steps
$var = <<HERE_TARGET;
your text
goes here
HERE_TARGET
$var =~ s/^\s+//gm;Discussion
The substitution is straightforward. It removes leading whitespace
from the text of the here document. The /m
modifier lets the ^ character match at the start
of each line in the string, and the /g modifier
makes the pattern matching engine repeat the substitution as often as
it can (i.e., for every line in the here document).
($definition = <<'FINIS') =~ s/^\s+//gm;
The five varieties of camelids
are the familiar camel, his friends
the llama and the alpaca, and the
rather less well-known guanaco
and vicuña.
FINISBe warned: all the patterns in this recipe use
\s
, which
will also match newlines. This means they will remove any blank lines
in your here document. If you don’t want this, replace
\s with [^\S\n] in the
patterns.
The substitution makes use of the property that the result of an
assignment can be used as the left-hand side of
=~. This lets us do it all in one line, but it only works when you’re assigning to a variable. When you’re ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access