Bootstrap FreeKB - Perl (Scripting) - Using grep
Perl (Scripting) - Using grep

Updated:   |  Perl (Scripting) articles

Let's say you have an array of fruit that contains the following elements. grep can be used to only to print the elements that contain "apple". This will print both apple and pineapple.

#!/usr/bin/perl
use strict;
use warnings;

my @fruit = qw(apple orange banana pineapple);
print grep(/apple/, @fruit);

 

A pipe can be used to grep for two or more matches.This will print apple and pineapple and orange.

print grep(/apple|orange/, @fruit);

 

A regular expression can be used to only print elements that are an exact match. This will print only apple and banana.

print grep(/^(apple|orange)$/, @fruit);

 

An exclamation point can be used to return elements that do not contain. This will print orange and banana.

print grep(!/apple/, @fruit);

 

An exclamation point can be used to return elements that are not an exact match. This will also print orange and banana.

print grep(!/^(apple|orange)$/, @fruit);

 


Grep the array

Grep can be used to update the array to only have the values that contain or match the grep expression.

@fruit = grep(/apple/, @fruit);

@fruit = grep { $_ eq "apple" } @fruit;

 


Variable

The Perl grep function cannot be stored in a variable. Instead, an if statement can be used. The "i" option here is to ignore case (e.g. case insensitive match).

foreach my $fruit (@fruit) {
  if ($fruit =~ /apple/i) { 
    my $apple_fruit = $fruit; 
  }
}

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 8a4457 in the box below so that we can be sure you are a human.