编辑:新 Perl 程序员的注意事项 : 这种机制不应用于多行注释!它有一个缺陷,降低了可读性。
在此 PerlMonks post on mechanisms to produce multiline comments in Perl ,阿比盖尔提供了这个,让我感到困惑:
The problem with just using a here document is that it will issue a warning under '-w'. It's much better to use the little known << >> operator.
<<q=~q>>;
This is a multiline comment.
q
运行它
-M0=Deparse
给出:" This is a multiline comment.\n" =~ //;
-e syntax OK
有人可以告诉我这是怎么回事吗?
最佳答案
阿比盖尔的回答有点幽默。实际上没有<< >>
运算符(不在 Perl 版本中 before 5.22 ),但有一个(我猜不是那么出名)<<
运算符(operator)。不是二元移位运算符,而是一元 here-document (heredoc for short) .它的一个简单形式是:
$long_string = <<EOF;
This is a long, multiline string.
It ends when EOF appears alone on a line.
It will be assigned to the \$long_string variable.
EOF
事实上,这就是 Abigail 答案背后的“多行注释”功能——多行字符串文字。其余的是有点混淆的 Perl。
<<
之后的裸字或带引号的字符串结束字符串文字。您可以使用 q
作为一个简单的词:<<q;
This is a multiline comment, or rather a string literal whose value is ignored.
q
要理解 Abigail 代码段的其余部分,将 here-document 重写为一个简单的字符串文字会有所帮助:
"This is a multiline comment.\n" =~ q>>;
好的,现在
q>>
是 q
quote-like operator与 >
作为分隔符。 q>>
相当于 ''
(一个非插值文字,恰好是空的)。所以字符串文字是 matched against an empty pattern .该匹配的结果无论如何都会被忽略,但这会破坏匹配结果变量( $1
、 $&
等)。
关于perl - 理解奇怪的 Perl 多行注释机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5443121/