How to check if a Perl array contains a particular value?


In Perl, we can check whether an array contains a particular value or not with the help of the "grep" keyword. The grep function in Perl is used to filter the input supplied in the function as a parameter out of the list of items. Similar to Linux, it uses the given input to find the matching value.

The grep() Method

"grep" is a built-in function in Perl, we can pass our regular expression inside this function. It will check the input for matching values and return a list based on whether the condition is true or false.

Syntax

As it is a built-in function in Perl, we do not need to include any libraries to use the grep() method. It has the following syntax −

grep(regular_expression, @my_array)

Now that we know a little about the "grep" function, let's try to understand it better with the help of a few examples.

Example 1

Consider the code shown below. Here we are not using the "grep" function. We will be simply printing the elements of an array, and then later we will add a "grep" keyword in the next example to find if the array contains a particular element or not.

use warnings;
use strict;
my @weekdays = qw(Mon Tue Wed Thu Fri Sat Sun);

print($weekdays[0]);
print("\n");
print($weekdays[2]);

Output

If you run the above code on a Perl compiler, you will get the following output on the terminal −

Mon
Wed

Here, we just created an array and then displayed its first and third elements.

Example 2

Now, let's use the "grep" method in the above example and see how it helps us to find the elements inside the array. Consider the code shown below.

use warnings;
use strict;
my @weekdays = qw(Mon Tue Wed Thu Fri Sat Sun);

print($weekdays[0]);
print("\n");
print($weekdays[2]);
print("\n");

if (grep(/^Mon/, @weekdays)) {
   print "found it";
} else {
   print "Not present in array";
}
print("\n");

if (grep(/^Ran/, @weekdays)) {
   print "found it";
} else {
   print "Not present in array";
}

Output

If you run the above code on a Perl compiler, then you will get the following output on the terminal.

Mon
Wed
found it
Not present in array

Observe that the first "grep" method returns "found it" because the word "Mon" is present in the array. In the second case, however, the "grep" method returns "Not present in array" because the word "Ran" is not present in the given array.

Updated on: 26-Dec-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements