gpt4 book ai didi

perl - 为什么在这个 Perl 示例中定义的 sdf 返回 true?

转载 作者:行者123 更新时间:2023-12-01 05:42:45 25 4
gpt4 key购买 nike

我在 Perl 中试过这个例子。有人可以解释为什么这是真的吗?

  if (defined sdf)  {   print "true";  }

它打印 true .

sdf 可以是任何名称。

此外,如果定义了 sdf 函数并且返回 0,则它不打印任何内容。
print (sdf);不打印 sdf 字符串,但
if (sdf eq "sdf")
{
print "true";
}

打印为真。

如果 sdf 是字符串,相关问题仍然存在。什么不是打印出来的?

最佳答案

sdfbareword .

perl -Mstrict -e "print qq{defined\n} if defined sdf"
Bareword "sdf" not allowed while "strict subs" in use at -e line 1.Execution of -e aborted due to compilation errors.

For more fun, try

perl -Mstrict -e "print sdf => qq{\n}"

Strictly speaking about use strict :

The subs aspect of use strict disables the interpretation of ``bare words'' as text strings. By default, a Perl identifier (a sequence of letters, digits, and underscores, not starting with a digit unless it is completely numeric) that is not otherwise a built-in keyword or previously seen subroutine definition is treated as a quoted text string:

@daynames = (sun, mon, tue, wed, thu, fri, sat);

However, this is considered to be a dangerous practice, because obscure bugs may result:

@monthnames = (jan, feb, mar, apr, may, jun,
jul, aug, sep, oct, nov, dec);

Can you spot the bug? Yes, the 10th entry is not the string 'oct', but rather an invocation of the built-in oct() function, returning the numeric equivalent of the default $_ treated as an octal number.



更正: (感谢@ysth)

E:\Home> perl -我们“打印 sdf”
未加引号的字符串“sdf”可能会在 -e 第 1 行与将来的保留字发生冲突。
名称 "main::sdf"仅使用一次:-e 第 1 行可能有错别字。
在未打开的文件句柄 sdf 上打印()在 -e 第 1 行。

如果将裸字提供给 print在间接对象槽中,它被当作要打印到的文件句柄。由于没有提供其他参数, print默认为打印 $_到文件句柄 sdf .自 sdf没有打开,失败了。如果您在没有警告的情况下运行它,您将看不到任何输出。另请注意:

E:\Home> perl -MO=Deparse -e "print sdf"
打印 sdf $_;

作为对这一观察的证实。另请注意:

E:\Home> perl -e "打印 asdfg, sadjkfsh"
-e 第 1 行的文件句柄后不允许使用逗号。

E:\Home> perl -e "打印 asdfg => sadjkfsh"
asdfgsadjkfsh

后者打印两个字符串,因为 =>如果 LHS 上的字符串仅由 'word' 字符组成,则自动引用 LHS 上的字符串,删除第一个参数的文件句柄解释。

所有这些例子都表明,使用裸词会带来许多惊喜。您应该 use strict以避免此类情况。

关于perl - 为什么在这个 Perl 示例中定义的 sdf 返回 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1646997/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com