我有一个文件句柄FILE
在 Perl 中,我想迭代文件中的所有行。以下有区别吗?
while (<FILE>) {
# do something
}
and
foreach (<FILE>) {
# do something
}
对于大多数用途,您可能不会注意到差异。然而,foreach
将每一行读入list (不是数组 http://perldoc.perl.org/perlfaq4.html#What-is-the-difference-between-a-list-and-an-array%3f)在逐行浏览之前,而while
一次读取一行。作为foreach
会使用更多内存并需要预先处理时间,通常建议使用while
迭代文件的行。
编辑(通过Schwern):foreach
循环相当于:
my @lines = <$fh>;
for my $line (@lines) {
...
}
不幸的是,Perl 没有像对范围运算符那样优化这种特殊情况(1..10
).
例如,如果我用 a 读取 /usr/share/dict/wordsfor
循环和一个while
循环并让他们在完成后睡觉我可以使用ps
查看该进程消耗了多少内存。作为控件,我包含了一个打开文件但不执行任何操作的程序。
USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND
schwern 73019 0.0 1.6 625552 33688 s000 S 2:47PM 0:00.24 perl -wle open my $fh, shift; for(<$fh>) { 1 } print "Done"; sleep 999 /usr/share/dict/words
schwern 73018 0.0 0.1 601096 1236 s000 S 2:46PM 0:00.09 perl -wle open my $fh, shift; while(<$fh>) { 1 } print "Done"; sleep 999 /usr/share/dict/words
schwern 73081 0.0 0.1 601096 1168 s000 S 2:55PM 0:00.00 perl -wle open my $fh, shift; print "Done"; sleep 999 /usr/share/dict/words
The for
程序消耗了近 32 兆的实际内存(RSS
列)来存储我的 2.4 meg /usr/share/dict/words 的内容。这while
循环一次仅存储一行,仅消耗 70k 的行缓冲。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)