760176104 发表于 2015-12-25 15:24:21

perl中的map和grep

map
  语法:
  map EXPR, LIST
  map BLOCK, LIST
  语义:
  对于LIST中的每个元素执行EXPR或者BLOCK,如果返回值存储在list中,则表示处理后的list,若返回值存储在scalar中,则表示处理后的list中元素个数。下面是几个例子.

单词首字母大写



sub test {
    my @names = (
      'jacob',
      'alexander',
      'ethan',
      'andrew',
    );
    my @new_names = map(ucfirst, @names);
    foreach my $name (@new_names) {
      print $name, "\n";
    }
}
打印数组元素
  print 相当于 print $_



my @row_ary = (1, 3, 'abc', undef, 12, 'ddd', undef, undef) ;
map { print } @row_ary;
替换数组元素
  对于数组中每个元素,如果其值是undef,那么将其替换位x。



my @row_ary = (1, 3, 'abc', undef, 12, 'ddd', undef, undef) ;
map { $_='x' unless $_ } @row_ary;
grep
  grep的语法格式与map完全一样,不过grep是通过判断列表中每个元素是否满足表达式或者块来返回true和false,再根据true和false来决定最终的返回列表。所以grep多时用来过滤元素用的。
  一个例子,找出一组单词中的纯数字单词,如下。



sub test {
    my @words = (
      'hello',
      '123',
      'B51',
      '123abc',
      '8',
    );
    my @numbers = grep { /^\d+$/ } @words;
  取数组中下标为奇数的元素



my @nums = (2, 1, 3, 5, 4, 6);
my @odd = @nums;
  @odd中值分别是1,5,6
  分析,$#nums表示数组nums最后一个元素的下标,grep { $_ & 1} 取奇数下标,@nums[]取下标为奇数的元素。

  

  ==
页: [1]
查看完整版本: perl中的map和grep