perl - 在 Perl 中,readline 如何在循环条件中分配给 $_ 而不是在其他地方?

标签 perl

在 Perl 中 readline 是如何实现的?

问题是为什么 readline 设置 $_ 如果 readline 用于循环条件,例如:

while(<>) {
  #here $_ is set
  print;
}

相反,如果我们只是这样做

<>;
print;  #$_ is not set here

它不会打印任何东西?

这是如何实现的?函数如何知道它在循环条件语句中使用?或者它只是这样设计的内置行为?

最佳答案

在这种情况下,readline 的实现没有什么特别之处。 .它从不设置 $_ .相反,Perl 编译器中有一个特殊情况,它检查 while 的条件。循环并在内部重写某些条件。

例如,while (<>) {}被改写成

while (defined($_ = <ARGV>)) {
    ();
}

您可以通过 perl -MO=Deparse -e 'while (<>) {}' 看到这一点.

这记录在 I/O Operators in perlop 下:

Ordinarily you must assign the returned value to a variable, but there is one situation where an automatic assignment happens. If and only if the input symbol is the only thing inside the conditional of a while statement (even if disguised as a for(;;) loop), the value is automatically assigned to the global variable $_, destroying whatever was there previously.

Loop Control & For Loops in perlsyn 中也提到过.

关于perl - 在 Perl 中,readline 如何在循环条件中分配给 $_ 而不是在其他地方?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30241230/

相关文章:

perl - redis HLL 误报太多

perl - 哪些 perl 代码示例会导致未定义的行为?

perl 匹配不同表中的两列

Perl Webservice SSL 协商失败

perl - 为什么在 BEGIN block 中首先执行 'use' 语句?

perl - 如何将参数传递给 Perl/Tk 中的子例程?

perl - Sed错误 "sed: no input files"

java - 无法使用 File.list() 读取目录

c++ - 如何读取 PRS/SKmapDat 文件?

perl - 如何在 Perl 中使用 else 单行语句?