Perl地图的要点是什么? [英] What's the point of Perl's map?

查看:93
本文介绍了Perl地图的要点是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

没有真正获得地图功能的要点。任何人都可以用例子来解释它的使用?



使用这个而不是一个循环或者只是糖?有什么性能好处吗?

解决方案

任何时候您想要根据另一个列表生成列表:

 #双重列表的所有元素
my @double = map {$ _ * 2}(1,2,3,4,5);
#@double =(2,4,6,8,10);

由于列表可以轻松地转换成散列,如果您希望基于特定对象的对象的哈希表属性:

 #@user_objects是具有unique_id()方法的对象列表
my%users = map { $ _-> unique_id()=> $ _} @user_objects;
#%users =($ id => $ obj,$ id => $ obj,...);

这是一个非常通用的工具,您只需开始使用它来在应用程序中找到良好的用途。



有些人可能会喜欢使用详细的循环代码进行可读性,但是我个人觉得 map 更可读。 >

Not really getting the point of the map function. Can anyone explain with examples its use?

Are there any performance benefits to using this instead of a loop or is it just sugar?

解决方案

Any time you want to generate a list based another list:

# Double all elements of a list
my @double = map { $_ * 2 } (1,2,3,4,5);
# @double = (2,4,6,8,10);

Since lists are easily converted pairwise into hashes, if you want a hash table for objects based on a particular attribute:

# @user_objects is a list of objects having a unique_id() method
my %users = map { $_->unique_id() => $_ } @user_objects;
# %users = ( $id => $obj, $id => $obj, ...);

It's a really general purpose tool, you have to just start using it to find good uses in your applications.

Some might prefer verbose looping code for readability purposes, but personally, I find map more readable.

这篇关于Perl地图的要点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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