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

前端 未结 6 777
逝去的感伤
逝去的感伤 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:15

    One other thing about grep: in a scalar context it tells you how many items it found. This can be useful if you don't really want a second list, but you do want to know how many items of a certain kind there are.

    my @numbers = qw/1 2 3 4 5 6/;
    
    my @odd_numbers  = grep { $_ & 1 } @numbers; # grep returns (1, 3, 5)
    
    my $how_many_odd = grep { $_ & 1 } @numbers; # grep returns 3
    

    Edit: Since the OP asked in a comment, I should say that you can use map in a scalar context in the same way. The point wasn't that grep is the only one of the two that can do this, but that it sometimes comes in handy to do this with grep.

提交回复
热议问题