我正在尝试读取文件,
while($line = $file_handle)
当我运行此代码时,程序挂起。
我注意到使用文件句柄读取文件,我们需要使用<>
while($line = <file_handle>)
后面的代码显然运行了。
现在我知道运算符 <> 是逐行读取文件,我想知道当我不提供 <> 运算符时到底发生了什么? 是不是找不到行尾?或者?
谢谢
最佳答案
鉴于此代码:
use warnings;
use strict;
open my $fh, '<', 'in.txt' or die $!;
while (my $x = $fh){
$DB::single=1;
print "$x\n";
}
在调试器中运行时,您可以看到 $x
现在包含 GLOB
(文件句柄的副本)。在每次迭代中,$x
将整个句柄作为赋值,并导致无限循环,因为该语句始终为 true。因为您总是分配一个真值(句柄),所以 while 语句实际上与编写 while(1){...
没有什么不同。 .
perl -d script.pl
main::(x.pl:4): open my $fh, '<', 'in.txt' or die $!;
DB<1> s
main::(x.pl:6): while (my $x = $fh){
DB<1> s
main::(x.pl:7): $DB::single=1;
DB<1> x $x
0 GLOB(0xbfdae8)
-> *main::$fh
FileHandle({*main::$fh}) => fileno(6)
DB<2> s
main::(x.pl:7): $DB::single=1;
DB<2> x $x
0 GLOB(0xbfdae8)
-> *main::$fh
FileHandle({*main::$fh}) => fileno(6)
<$fh>
本质上是从文件句柄中提取一行,当遇到 EOF(或发生错误)时,返回 undef
,它终止循环(因为 undef
为 false)。
关于perl - 使用文件句柄读取文件的运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37578417/