在 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 afor(;;)
loop), the value is automatically assigned to the global variable$_
, destroying whatever was there previously.
关于perl - 在 Perl 中,readline 如何在循环条件中分配给 $_ 而不是在其他地方?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30241230/