What's the difference between grep and map in Perl?

前端 未结 6 740
逝去的感伤
逝去的感伤 2020-12-31 06:50

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

What is the difference b

6条回答
  •  时光说笑
    2020-12-31 07:06

    Think of grep as map with a filter. map iterates and provides an opportunity to do something with every item. For example these two lines are equivalent:

    my @copy = @original;
    my @copy = map {$_} @original;
    

    Similarly, these two are equivalent:

    my @copy = grep {-f $_} @original;
    
    @copy = ();
    for (@original)
    {
      push @copy, $_ if -f $_;
    }
    

    grep provides the ability to insert a conditional, and therefore becomes a filter.

提交回复
热议问题