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

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

问题描述

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

In Perl, if you have a loop like this:

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

您可以在无效上下文中使用对 map 的调用来替换它:

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 开始 空上下文中的映射并不昂贵:

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

空上下文中的映射不再是昂贵的.地图现在是上下文感知的,并且不会构造一个列表,如果在空上下文中调用.

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

但是for的后缀形式可能更具可读性:

But the postfix form of for may be more readable:

perform_action($_) for @items;

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

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