问题描述
我在 Perl 中有一个文件句柄 FILE
,我想遍历文件中的所有行.以下有区别吗?
I have a filehandle FILE
in Perl, and I want to iterate over all the lines in the file. Is there a difference between the following?
while (<FILE>) {
# do something
}
和
foreach (<FILE>) {
# do something
}
推荐答案
在大多数情况下,您可能不会注意到差异.但是,foreach
将每一行读入列表(不是数组),然后一行一行地遍历它,而 while
在一个时间.由于 foreach
将使用更多内存并需要预先处理时间,因此通常建议使用 while
来遍历文件的行.
For most purposes, you probably won't notice a difference. However, foreach
reads each line into a list (not an array) before going through it line by line, whereas while
reads one line at a time. As foreach
will use more memory and require processing time upfront, it is generally recommended to use while
to iterate through lines of a file.
编辑(通过 Schwern):foreach
循环相当于:
EDIT (via Schwern): The foreach
loop is equivalent to this:
my @lines = <$fh>;
for my $line (@lines) {
...
}
遗憾的是,Perl 没有像对范围运算符 (1..10
) 那样优化这种特殊情况.
It's unfortunate that Perl doesn't optimize this special case as it does with the range operator (1..10
).
例如,如果我使用 for
循环和 while
循环读取/usr/share/dict/words 并让它们在完成后睡眠,我可以使用 ps
查看进程消耗了多少内存.作为一个控件,我包含了一个打开文件但不执行任何操作的程序.
For example, if I read /usr/share/dict/words with a for
loop and a while
loop and have them sleep when they're done I can use ps
to see how much memory the process is consuming. As a control I've included a program that opens the file but does nothing with it.
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
for
程序消耗了近 32 兆的实际内存(RSS
列)来存储我的 2.4 兆/usr/share/dict/words 的内容.while
循环一次仅存储一行,仅消耗 70k 用于行缓冲.
The for
program is consuming almost 32 megs of real memory (the RSS
column) to store the contents of my 2.4 meg /usr/share/dict/words. The while
loop only stores one line at a time consuming just 70k for line buffering.
这篇关于在 Perl 中使用 foreach 或 while 迭代文件有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2