Friday, July 29, 2011

grep in perl


1)grep in perl can be used to search a pattern in a array and print the values that match to a array.


@a=('one','Two','Three','Four','Five');
@ff=grep(/^T/,@a);
print "@ff";


G:\perl_programs>perl perl_grep.pl
Two Three
G:\perl_programs>

Explanation:
Here the pattern searched through arrays is "^T".So here Two and Three values match and it is assigned to the array.

2)grep can also be used to find no of values in a array match the pattern specified by assigning to the scalar.
using the below example:

@a=('one','Two','Three','Four','Five');
$ff=grep(/^T/,@a);
print "$ff";

Output:

G:\perl_programs>perl perl_grep.pl
2
G:\perl_programs>

Explanation:
Here the pattern searched through arrays is "^T".So here Two and Three values match Since it is assigned to a scalar it is converted to 2(no of values that match).

3)It can also be used to process the arrays such as substitute ceratin content of array likewise


@a=('one','Two','Three','Four','Five');
$ff=grep(s/Two/zero/,@a);
print "The no of values where it was substituted:$ff"."\n";
print "The changed array:@a"."\n";

Output:

G:\perl_programs>perl perl_grep.pl
The no of values where it was substituted:1
The changed array:one zero Three Four Five

G:\perl_programs>

Explanation:
Here the grep function is used to substitute Two with zero by moving through every array content.

4)grep function can also be used to print the array content .But it is not preferred it is better to use map function for that:

@a=('one','Two','Three','Four','Five');
$ff=grep(print("$_\n"),@a);


Output:


G:\perl_programs>perl perl_grep.pl
one
Two
Three
Four
Five
G:\perl_programs>

No comments:

Post a Comment