理解奇怪的Perl多行注释机制 [英] Understanding strange Perl multiline comment mechanism

查看:186
本文介绍了理解奇怪的Perl多行注释机制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:新的Perl程序员注意:此机制不应用于多行注释!

Note to new Perl programmers: This mechanism should NOT be used for multiline comments! It has a flaw decreases readability.

在此 PerlMonks帖子上的机制在Perl中产生多行注释,Abigail提供了这一个,困惑我:

In this PerlMonks post on mechanisms to produce multiline comments in Perl, Abigail provided this one, that perplexes me:


使用here文档的问题是它会在-w下发出警告。这是更好的使用知名的<< >> operator。

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

有人可以告诉我发生了什么吗?

Can someone tell me what is going on?

推荐答案

Abigail的答案是部分幽默的。事实上没有<< >> 运算子(不适用于Perl版本 before 5.22 ),但有一个(不是众所周知的,我猜)< <$ / code>运算符。不是二进制移位运算符,而是一元的 here-document(简称heredoc)。其简单形式是:

Abigail's answer is partly humorous. There is in fact no << >> operator (not in versions of Perl before 5.22), but there is a (not that well-known, I guess) << operator. Not the binary shift operator, but the unary here-document (heredoc for short). A simple form of it is:

$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答案的多行字符串文字。

This is, in fact, the "multiline comment" feature underlying Abigail's answer — a multiline string literal. The rest is a bit of somewhat obfuscated Perl.

<< 结尾处的裸字或引号字符串字符串字面量。您可以使用 q 作为一个裸词:

The bareword or quoted string after << ends the string literal. You can use q as a bareword:

<<q;
This is a multiline comment, or rather a string literal whose value is ignored.
q

要了解Abigail的其他代码片段,它有助于重写here-一个简单的字符串字符串:

To understand the rest of Abigail's snippet, it helps to rewrite the here-document into a simple string literal:

"This is a multiline comment.\n" =~ q>>;

好,现在 q>> q 引用运算符,其中> 为分隔符。 q>> 等效于''(非插值文字,其恰好为空)。因此,字符串文字是与空模式匹配 。匹配的结果被忽略,但这会破坏匹配结果变量( $ 1 $& 等)。

Ok, now q>> is the q quote-like operator with > as the delimiter character. q>> is equivalent to '' (a non-interpolated literal, which happens to be empty). So the string literal is matched against an empty pattern. The result of that matching is ignored anyway, but this clobbers the match result variables ($1, $&, etc).

这篇关于理解奇怪的Perl多行注释机制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆