Eri*_*itt 6 perl memory-management file map filehandle
map { function($_) } <FILEHANDLE>;使用perl时调用是否将整个文件加载到内存中?
是的 - 或者至少我是如何解释这个结果的.
$ perl -e "map {0} <>" big_data_file
Out of memory!
$ perl -e "map {0} 1 .. 1000000000"
Out of memory!
Run Code Online (Sandbox Code Playgroud)
人们可能想知道我们是否因为Perl试图存储输出而耗尽内存map.但是,我的理解是Perl经过优化,可以map在void上下文中调用时避免这种工作.有关具体示例,请参阅此问题中的讨论.
或许更好的例子:
$ perl -e "sub nothing {} map nothing(), <>" big_data_file
Out of memory!
Run Code Online (Sandbox Code Playgroud)
基于这些评论,似乎问题的动机是在处理大数据时需要紧凑的语法.
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>;
Run Code Online (Sandbox Code Playgroud)