FreeKB - Perl Using grep
Perl - Using grep

Let's say you have an array named fruit that contains values, such as apple, orange, and banana.

@fruit = qw(apple orange banana pineapple);


Printing this array will display apple, orange, banana, and pineapple.

print @fruit;



If you only want to print fruit that contains the string "apple", grep can be used. This will print both "apple" and "pineapple".

print grep(/apple/, @fruit);


Since this uses forward slashes, if the value being checked contains forward slashes, you will need to escape the forward slashes.

print grep(/\/path\/to\/directory/, @fruit);


Does not contain

Use an exclamation point to return items to do not match. In this example, only fruit that does not contain "apple" will be printed.

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


Exact match

If you want to only return exact matches, us this syntax. In this example, "apple" will be printed and "pineapple" will not be printed.

foreach my $fruit (@fruit) {
  if (grep { $fruit eq "apple" } @fruit) {
    print $fruit;


Is not an exact match

Use "ne" (not equal) to return items to do not match. In this example, only fruit that does not match "apple" will be printed.

foreach my $fruit (@fruit) {
  if (grep { $fruit ne "apple" } @fruit) {
    print $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;



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 bf581 in the box below so that we can be sure you are a human.


Web design by yours truely - me, myself, and I   |   |