Using grep with Perl

Home > Search

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

@fruit = qw(apple orange banana);


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

print @fruit;


If you only want to print fruit that contains the letter e, grep can be used.

print grep(/e/, @fruit);


Do not match

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

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



If you want to store the result of grep, it should be stored in an array (not a variable).

@array = grep(/e/, @fruit);



The Perl grep function cannot be stored in a variable. Instead, and if statement can be used.

foreach my $fruit (@fruit) {
  if ($fruit =~ "e") { 
    my $e_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 in the box below so that we can be sure you are a human.