Perl 中提供类似于Unix Shell中的“此处文档”功能的操作符“<<”.
具体使用的例子如下:
1:
print <<" EOF"; #可以为任意字符串(包括空),也无需大写,为了便于查看最好采用大写字符。
Hello World.
EOF #注意该值要顶行书写,否则报错。
2:
print << x 10; #打印行("Hello World.")10次
Hello World.
print << "" x 10; #实现上面内容的比较好的方法,相当于使用"空"字符串进行标识
The Camels are coming! Hurrah! Hurrah!
3:执行多条命令
$a = << `EOC`; # 执行多条命令
echo hi there
echo lo there
EOC
上述操作等价于 $a = qx/echo ni there;echo ni there/;
4: 堆叠使用
print <<" dromedary", <<" camelid";
I said bactrian.
dromedary
5: 函数调用中使用
&function(<<" THIS",23,<<' THAT');
Here's a line
ro two.
THIS
And here's another.
THAT
sub function {
my ($first,$second,$three) = @_;
print "First = $first";
print "Second = $second";
print "Three = $three";
}
如果你的此处文档在你的其他代码里是缩进的,你就得手工从每行删除开头的空白:
($quote = <<'QUOTE') =~ s/^\s+//gm;
The Road goes ever on and on, down from the door where it began.
QUOTE
你甚至还可以用类似下面的方法用一个此处文档的行填充一个数组:
@sauces = <<End_Lines =~ m/(\S.*\S)/g;
normal tomato
spicy tomato
green chile
pesto
white wine
具体使用的例子如下:
1:
print <<" EOF"; #可以为任意字符串(包括空),也无需大写,为了便于查看最好采用大写字符。
Hello World.
EOF #注意该值要顶行书写,否则报错。
2:
print << x 10; #打印行("Hello World.")10次
Hello World.
print << "" x 10; #实现上面内容的比较好的方法,相当于使用"空"字符串进行标识
The Camels are coming! Hurrah! Hurrah!
3:执行多条命令
$a = << `EOC`; # 执行多条命令
echo hi there
echo lo there
EOC
上述操作等价于 $a = qx/echo ni there;echo ni there/;
4: 堆叠使用
print <<" dromedary", <<" camelid";
I said bactrian.
dromedary
She said llama.
camelid
5: 函数调用中使用
&function(<<" THIS",23,<<' THAT');
Here's a line
ro two.
THIS
And here's another.
THAT
sub function {
my ($first,$second,$three) = @_;
print "First = $first";
print "Second = $second";
print "Three = $three";
}
如果你的此处文档在你的其他代码里是缩进的,你就得手工从每行删除开头的空白:
($quote = <<'QUOTE') =~ s/^\s+//gm;
The Road goes ever on and on, down from the door where it began.
QUOTE
你甚至还可以用类似下面的方法用一个此处文档的行填充一个数组:
@sauces = <<End_Lines =~ m/(\S.*\S)/g;
normal tomato
spicy tomato
green chile
pesto
white wine
End_Lines