Saturday, July 30, 2011

map vs grep in perl


grep function in perl:
grep function is normally used to select the matched pattern and return it to the array

grep(EXPRESSION,@array);
grep(BLOCK,@array);

Perl file:

$"="\n";
$\="\n";
@array=(0..3,"karthik");
print "@array";
@result=grep($_=~ s/0/9/,@array);
print "array:\n@array";
print "result:\n@result";

output:

G:\perl_programs>perl perl_map.pl
0
1
2
3
karthik
array:
9
1
2
3
karthik
result:
9

G:\perl_programs>

Analysis:
In this case if you see the grep function tries to substitute 0 with 9 by moving through each element of the array.When it finds a element with value 0 it
modifies the original array and returns the replaced value to the result array.
So as you may see from the output the result array has only one value "9".

Map function in perl:
Map function is used to evaluate the given expression and return t
he result value to the array.


$"="\n";
$\="\n";
@array=(0..3,"karthik");
print "@array";
@result=map($_=~ s/0/9/,@array);
print "array:\n@array";
print "result:\n@result";


Output:

G:\perl_programs>perl perl_map.pl
0
1
2
3
karthik
array:
9
1
2
3
karthik
result:
1






G:\perl_programs>

Analysis:
In this case if you see the map function tries to substitute 0 with 9 by moving through each element of the array similar as in grep.But When it does not 
find the match it returns empty string to the result array and when it finds the match it modifies the original array with the substituted value and returns the "1" to the result array which is the return value for pass or fail for the substitution.
So as you may see from the output the result array has only one value "1" followed
by space for the values which did not match.

No comments:

Post a Comment