Perl grep() Function for Array Elements Search

What is grep() Function in Perl programming?

Explanation

The grep() function browse through a list, to find elements in an array based on the criteria given.

Syntax:


grep EXPR,LIST;
grep BLOCK,LIST;

In the above syntax, grep() function takes a regular expression, a list as arguments.

Example :


#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
@color = ('Green' , 'Orange', 'Blue', 'Pink', 'Peach', 'Black');
@col1 = (grep(/^P/, @color));
print ("The strings starting with P: ", @col1,"n");
print "<br>";
@col2 = (grep(!/^P/,@color));
print ("The strings not starting with P: ", @col2,"n");
Result :

The strings starting with P: PinkPeach
The strings not starting with P: GreenOrangeBlueBlack

In the above example first the elements that match the starting character "P" are listed, next the elements not starting with "P" are listed, both these are done using a regular expression.

Ask Questions

Ask Question