How to check if a Perl array contains a particular value

Overview

In Perl, an array is a special type of variable that is used to store a list of elements.

There are multiple ways to check if an array contains a particular value. In this shot, we will use grep().

The grep() method

The method uses regexregular expression is a sequence of characters that specifies a search pattern in text to check if the given value is present in the given array.

Syntax

grep( /^$value$/, @nums )
Syntax of grep() function

Parameters

It takes two parameters value and array.

  • value: Provides value to search for.
  • array: Provides array to search in.

Return value

It returns a boolean value.

Example

In the following example, we will check if the given value 90 is present in the given array nums or if it's using grep().

Code

#provide nums array
@nums = (10, 20, 30, 40 , 50);
#provide value to search
my $value = 90;
#check if array contains given value
if ( grep( /^$value$/, @nums ) ) {
print "The given value contains in the array";
}else{
print "The given value does not contain in the array";
}

Explanation

In the code snippet above:

  • In Line 2: We declare and initialize the array nums.
  • In Line 5: We declare and initialize the value to search in the array.
  • In Line 8: We check if the given value is present in the given array using grep(). We will provide the output statement according to the return value from grep().

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources