Perl 内存使用情况以及映射和文件句柄
使用 perl 时调用 map { function($_) }
是否会将整个文件加载到内存中?
Does calling map { function($_) } <FILEHANDLE>;
load the entire file into memory when using perl?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的——或者至少我是这么解释这个结果的。
人们可能想知道我们是否耗尽了内存,因为 Perl 正在尝试存储
map
的输出。然而,我的理解是,Perl 进行了优化,以避免在 void 上下文中调用map
时的工作。有关具体示例,请参阅此问题中的讨论。也许是一个更好的例子:
根据评论,这个问题似乎是出于在处理大数据时对紧凑语法的渴望而提出的。
Yes -- or at least that's how I interpret this outcome.
One might wonder whether we run out of memory because Perl is trying to store the output of
map
. However, my understanding is that Perl is optimized to avoid that work whenevermap
is called in a void context. For a specific example, see the discussion in this question.Perhaps a better example:
Based on the comments, it appears that the question is motivated by a desire for a compact syntax when processing large data.
是的,
map
、foreach 循环和 sub 调用的操作数在map
、foreach 循环或 sub 调用甚至开始之前计算。一个例外:(
有或没有
my $i
)被优化为计数循环,类似Perl6 的东西将对惰性列表提供本机支持。
Yes, the operands for
map
, foreach loop and sub calls are evaluated beforemap
, the foreach loop or the sub call even begins.One exception:
(with or without
my $i
) is optimised into a counting loop, something along the lines ofPerl6 will have native support for lazy lists.
我假设您问的问题是这样的:
map
函数是否在开始处理之前读取文件,或者是否逐行使用。让我们快速比较一下处理列表:
这个例子显然是逐行使用的。每次迭代,都会获取
$_
的新值。在这种情况下,
LIST
在循环开始之前展开。在http://perldoc.perl.org/functions/map.html中有一个引用map
类似于foreach
循环,并且我确实相信LIST
在传递给函数之前会被扩展。The question you are asking I assume is this: Does the
map
function slurp the file before it begins processing, or does it use line by line.Lets do a quick comparison about handling lists:
This case clearly uses line by line. Each iteration, a new value for
$_
is fetched.In this case, the
LIST
is expanded before the loop starts. In http://perldoc.perl.org/functions/map.html there is a reference tomap
being similar to aforeach
loop, and I do believe thatLISTs
are expanded before being passed to a function.