Sunday, December 29, 2013

What is the diff between grep and map function?

The main diff between grep and map is, grep returns those elements of the original list that match the expression, while map function runs an expression on each element of an array, and returns a new array with the results.

For Example:

map()

#!/usr/bin/perl -w
@myNames = ('jac', 'alex', 'ethan', 'andrew'); 
@ucNames = map(ucfirst, @myNames); 

foreach $key ( @ucNames ){ 
print "$key\n";
}

The above example returns all element from myNames array with first letter in uppercase.
So it means map applied ucfirst function on each elements of array.


grep()

@list = (1,"Test", 0, "foo", 20 ); 
@has_digit = grep ( /\d/, @list ); 
print "@has_digit\n";
 
The above example returns all digits from list array.
So it means grep locate elements in a list for which given expression is true.

Note:
Both function returns the number of times the expression returned true in scalar context and list of elements that matched the expression in list context.


Source: http://perlinterview.blogspot.in/2013/12/what-is-diff-between-grep-and-map.html

No comments: