这两个Perl片段有什么区别?

use*_*747 7 perl heredoc

print <<EOF
stuff
EOF
;


print <<EOF;
stuff
EOF
Run Code Online (Sandbox Code Playgroud)

你为什么要用另一个呢?

Eth*_*her 14

这两个例子在行为上是相同的,但考虑一下你打算在打印那个块之后做些什么:

print <<EOF
stuff
EOF
. "more text here";
Run Code Online (Sandbox Code Playgroud)

...或者您可能需要测试操作的结果:

print $unstable_filehandle <<EOF
stuff
EOF
or warn "That filehandle finally disappeared: $!";
Run Code Online (Sandbox Code Playgroud)

这些示例是人为设计的,但您可以看到,有时可以灵活地了解文本块之后的代码.


Sir*_*ert 9

正如tchrist指出的那样,大多数人忽略的一件事是heredoc运算符在终止代码之后采用任意perl代码.

这意味着您可以(可以说)进行更自然的操作,例如:

my $obj = Foo::Bar->new(content => <<EOP)->do_stuff->sprint();
    This is my content
    It's from a heredoc.
EOP
Run Code Online (Sandbox Code Playgroud)

一个结果是,您可以将它们堆叠得更多(在我看来),而不是"未堆叠":

-- stacked_heredoc.pl
#!/usr/bin/perl
use strict;
use warnings;

print join(<<JOINER, split("\n", <<SOURCE));

------------------------------
JOINER
This is my text
this is my other text
a third line will get divided!
SOURCE
Run Code Online (Sandbox Code Playgroud)

一个未被堆积的heredoc ...

-- unstacked_heredoc.pl
#!/usr/bin/perl
use strict;
use warnings;

my $joiner = <<JOINER

------------------------------
JOINER
;

my $source = <<SOURCE
This is my text
this is my other text
a third line will get divided!
SOURCE
;

print join($joiner, split("\n", $source));
Run Code Online (Sandbox Code Playgroud)