开发者

Can I use a here document to append to a string?

I have a string that I want to append a block of formatte开发者_如何学编程d SQL to. Is there a way to append using a here document? Or do I need to create a new string using the here document and append that to the existing string?


You could probably say

    $str = <<EOH;
$str
more stuff here
EOH

but Perl optimizes that to

    $str .= <<EOH;
more stuff here
EOH

You should not need to set up a separate variable as in

    $str1 = <<EOH;
more stuff here
EOH
    $str .= $str1;

; even in older Perls the previous two should work fine (whereas with very old Perl 5 there were some cases that didn't work, notably print <<EOH; would lose the contents of the here document).


Here docs are very flexible, and can be used in most situations you would use a normal string literal. They can be used as a part of a function call or compound expression.

my $inner_str = 'middle text';

my $full_str = <<FIRST_BLOCK . "$inner_str\n" . <<SECOND_BLOCK;
This text is at the start of the string.
And so is this.
FIRST_BLOCK
This text ends the first assignment to the string.
SECOND_BLOCK

The rules Perl use to parse the heredoc allow for some very strange behavior, when a heredoc is found the current line will continue to be parsed until that line ends. Then perl will stop parsing the current expression and start reading the heredoc until if finds the end token. Once it finds end tokens for all heredocs that were started on that line it will resume parsing as if there was not an interruption in the expression.

$full_str .= <<THIRD_BLOCK . "$inner_str
This text is "appended" to the string.
THIRD_BLOCK
" . <<LAST_BLOCK;
This text ends the string.
LAST_BLOCK

print $full_str;

Note that the string starts before the body of the heredoc THIRD_BLOCK, and ends after the heredoc THIRD_BLOCK, but doesn't include its contents.

While you can be very flexible with the heredoc syntax I recommend you only use one heredoc per expression, keep the expression simple. If you need multiple heredocs in one expression or need one in a complex expression then assign the heredoc to a variable first and use that variable in the expression.


Yes, you can.

$sql = "select something";
print <<END
Line 1
Line 2
Line 3
END
. $sql;

outputs:

Line 1
Line 2
Line 3
select something
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜