perl - 理解奇怪的 Perl 多行注释机制

标签 perl operators comments

编辑:新 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/

相关文章:

perl - 如何在 .pl 和 .bat 文件中暂停控制台窗口?

java - Java 中的 ^ 运算符有什么作用?

需要 Java 运算符 "not equal to"帮助

java - 用于拆分字符串以获取运算符的正则表达式

intellij-idea - 在 IntelliJ 代码编辑器中的方法之间画线

c++ - 在 C++ 中评论

swift - Swift3 中多返回值函数的文档注释

perl - 分析图像复杂度

perl - 如何用驼鹿正确打开管道?

php - 需要 "pack"的帮助,用于 perl 和 php