What is Grep used for in Perl?

Questions by ms_2007

Showing Answers 1 - 12 of 12 Answers

Valee

  • Nov 12th, 2007
 

You can able check the array contains a particular value is exist or not? For example see the below code.

@array = (1,2,3,4,5,6,7,8,100,200,500); # array
$result = grep(/600/, @array); # checking the value.
print $result; # the result will be 0. (if 1 then it contains the value)

"grep" is a built function which extract all elements in ARRAY, matched by regex/pattern given as argument for grep and return the resultant elements in an array.


perl syntax: 
      ARRAY = grep PATTERN,  ARRAY

example one liner:-

perl -e '@a = qw (apple ball cat duck egg fish); print join " ", grep (/a/, @a) ; ' 

  Was this answer useful?  Yes

vasu

  • Dec 19th, 2011
 

Code
  1. #!/usr/bin/perl

  2. use strict;

  3. use warnings;

  4. my @myNames = (Jacob, Michael, Joshua, Matthew, Alexander, Andrew);

  5. my  @grepNames = grep(/^m(.*)$/i, @myNames);

  6. foreach my $grepNames (@grepNames) {

  7.         print"the value is :".$grepNames."

  8. ";

  9. }

  10.  

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions