Google


Perl GREP

grep EXPR,LIST

This is similar in spirit to, but not the same as, grep(1) and its relatives. In particular, it is not limited to using regular expressions.

Evaluates the BLOCK or EXPR for each element of LIST (locally setting $_ to each element) and returns the list value consisting of those elements for which the expression evaluated to true. In scalar context, returns the number of times the expression was true.

Example 1: Finding unique array elements
    my @arr = (7, 2, 3, 4, 7, 1, 3, 7, 1);
    say "@arr";
    Prints: 7 2 3 4 7 1 3 7 1
    my %seen = ();
    my @unique = grep { ! $seen{$_}++ } @arr;
    say "@unique";
    Prints: 7 2 3 4 1 

Example 2: Extracting odd numbers from an array
    my @arr = (1, 2, 3, 4, 5, 6, 7, 8, 9);
    say "@arr";
    Prints: 1 2 3 4 5 6 7 8 9
    my %seen = ();
    my @unique = grep { $_ & 1 } @arr;
    say "@unique";
    Prints: 1 3 5 7 9 

Example 3: Extracting word starting with 'a' or 'A' from a list
    my @arr = ("adam", "george","Albert" ,"Samual", "Carter");
    say "@arr";
    Prints: adam george Albert Samual Carter
    my %seen = ();
    my @starts_with_a = grep { /^a/i } @arr;
    say "@starts_with_a";
    Prints: adam Albert 

www.oocgi.com.