Perl 中的 grep 和 map 有什么区别? [英] What's the difference between grep and map in Perl?

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

问题描述

在 Perl 中,grepmap 都接受一个表达式和一个列表,并为列表中的每个元素计算表达式.

In Perl both grep and map take an expression and a list, and evaluate the expression for each element of the list.

两者有什么区别?

推荐答案

grep 返回原始列表中匹配表达式的那些元素,而 map 返回结果应用于原始列表的每个元素的表达式.

grep returns those elements of the original list that match the expression, while map returns the result of the expression applied to each element of the original list.

$ perl -le 'print join " ", grep $_ & 1, (1, 2, 3, 4, 5)'
1 3 5
$ perl -le 'print join " ", map $_ & 1, (1, 2, 3, 4, 5)'
1 0 1 0 1

第一个示例打印列表的所有奇数元素,而第二个示例根据相应元素是否为奇数打印 0 或 1.

The first example prints all the odd elements of the list, while the second example prints a 0 or 1 depending on whether the corresponding element is odd or not.

这篇关于Perl 中的 grep 和 map 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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