下面的奎因是如何工作的?

How does the following quine work?

根据维基百科:

A quine is a non-empty computer program which takes no input and produces a copy of its own source code as its only output

我看到了这段 perl 代码,但无法弄清楚它是如何工作的。

Save the following line in file /tmp/p and run the file as perl /tmp/p:

Illegal division by zero at /tmp/p line 1.

perl /tmp/p 的输出是:

Illegal division by zero at /tmp/p line 1.

代码如何工作?

首先,尝试 运行 打开警告:

$ perl -w p
Unquoted string "at" may clash with future reserved word at p line 1.
Unquoted string "tmp" may clash with future reserved word at p line 1.
Argument "tmp" isn't numeric in division (/) at p line 1.
Argument "at" isn't numeric in division (/) at p line 1.

前两个警告来自编译阶段。

让我们看看 Deparse 输出:

$ perl -MO=Deparse p
'division'->Illegal('zero'->by('at' / 'tmp' / 'line'->p(1)));
p syntax OK

本质上,at除以tmp的值除以另一个方法调用return的值p作为参数传递给方法by 在 class 'zero' 上调用。 attmp 被认为是字符串,它们的数值为零。因此,at/tmp导致非法除以零错误。

如果您将文件内容更改为

,您将得到同样的错误

Whosebug hacker news one at /tmp/p line 1.

如果您想知道 Illegal division 如何变成 'division'->Illegal,请参阅 indirect object syntax, and avoid using it

我更愿意看到你专​​注于提高 Perl 代码的质量,而不是研究晦涩的角落

但答案是该行被解析为

'division'->Illegal('zero'->by('at' / 'tmp' / 'line'->p(1)));

并且 Perl 在 'at''tmp' 中使用零,因为它们不是有效的数字字符串,所以第一个操作是计算 0 / 0,这会抛出错误