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 = ('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.

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

 

Printing myfruit will now only display fruit that contains the letter e, which would print apple and orange, but not banana.

print @myfruit;

 


Variable (not an array)

There is a different approach when working with a variable that contains a string of text instead of an array. For example, lets say you have a variable named content that contains a string of text.

my $content = "Hello World.  
How are you today.  
Goodbye Earth.";

 

If you only want to print lines that contain the word Earth, the following will do. In this example, this would print the line "Goodbye Earth".

print "$content\n" =~ /.*Earth.*/mg;

 



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