使用perl时,调用map { function($_) } <FILEHANDLE>;
是否会将整个文件加载到内存中?
最佳答案
是的-或至少这就是我解释这一结果的方式。
$ perl -e "map {0} <>" big_data_file
Out of memory!
$ perl -e "map {0} 1 .. 1000000000"
Out of memory!
有人可能想知道我们是否用完了内存,因为Perl试图存储
map
的输出。但是,我的理解是,每当在void上下文中调用map
时,都会对Perl进行优化以避免该工作。有关特定示例,请参见this question中的讨论。也许是更好的示例:
$ perl -e "sub nothing {} map nothing(), <>" big_data_file
Out of memory!
基于这些评论,似乎该问题是由于在处理大数据时对紧凑语法的需求而引起的。
open(my $handle, '<', 'big_data_file') or die $!;
# An ordinary while loop to process a data file.
while (my $line = <$handle>){
foo($line);
}
# Here Perl assigns each line to $_.
while (<$handle>){
foo($_);
}
# And here we do the same thing on one line.
foo($_) while <$handle>;
关于perl - 带有映射和文件句柄的Perl内存使用情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6088726/