perl - 带有映射和文件句柄的Perl内存使用情况

标签 perl file map memory-management filehandle

使用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/

相关文章:

perl - 从命令行调用 perl 子例程

java - 如果我的 .txt 文件为空,如何修复扫描仪错误?

c# - 由旧 C 代码编写的文件,已移至 C#

perl - Perl 中的快速字符串校验和函数生成 0..2^32-1 范围内的值

regex - Perl 文件逐行读取 (RegEx)

Perl 命令更改文件 EOL 并以相同名称保存文件

php - 写入一个具有一个函数的文件

r - ggplot2 和 map : geom_point and annotation_raster position mismatch

javascript - 什么是商业应用程序的好 map api?

ios - MapBox 水域/陆地检测