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.

finding the count of a certain character in a line perl


Perl Program:

$_="great,awesome.wonderful  wonder";
$dd=tr/w//;
print "count of character w is :$dd";

Output:

G:\perl_programs>perl perl_tr.pl
count of character w is :3

G:\perl_programs>
Analysis:
Here i have used tr operator to find the count of character 'w'.tr operator is normally used to translate the characters.But in this case i have translatted 'w' into
nothing as per the pattern "tr/w//".So it just returns the no of character matched in the line.