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

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; 
  }
}

 

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




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




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |