在Perl中,是否适合在void context中使用map而不是foreach循环? [英] In Perl, is it appropriate to use map in void context instead of a foreach loop?

查看:157
本文介绍了在Perl中,是否适合在void context中使用map而不是foreach循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Perl中,如果你有这样的循环:

In Perl, if you have a loop like this:

foreach (@items) {
    perform_action($_);
}

您可以将其替换为 map 在void context中:

you can replace it with a call to map in void context:

map {
    perform_action($_)
} @items;

有什么优点或缺点吗?它是否具有性能影响,因为Perl认为它必须保存结果?是否改善/改善可读性?

Are there any advantages or disadvantages to doing to? Does it have a performance impact because Perl thinks it has to save the results? Does it improve/worsen readability?

推荐答案

从Perl开始 5.8.1 在void上下文中的映射并不昂贵:

Starting from Perl 5.8.1 map in void context is not expensive:


不再
昂贵。地图现在上下文感知
,如果$ void
在void context中调用,则不会构造一个列表。

map in void context is no longer expensive. map is now context aware, and will not construct a list if called in void context.

但是的后缀表单可能更易读:

But the postfix form of for may be more readable:

perform_action($_) for @items;

这篇关于在Perl中,是否适合在void context中使用map而不是foreach循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆