Using grep with Perl

Home > Search
  by

Let's say you have a variable names fruit that contains an array of 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);

 


Array

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

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

 


Variable

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

foreach $fruit (@fruit) {
  if ($fruit =~ "e") { $efruit = $_ }
}

 

 



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.




Comments