{

How can I check if a Perl array contains a particular value?


This tutorial explains and Check If Element Exists in an Array of Perl With Code Examples.

we’ll take a look at a few different examples of Check If Element Exists In Array Perl

How do you check if an element in an array exists in Perl?

There are multiple ways we can check

  • using linear search

With linear Search, arrays are iterated sequentially and every element is checked for an element that exists or not.

Use for loop to iterate an array, and $_ contains the temporary variable to hold iterated element, and checked against search element using if conditional statement. Here is an example

@numbers = (1, 2, 3,4,5,6);
my $searchElement=1;

for (@numbers) {
    if ($_ eq $searchElement) {
       print "exists";
       last;
    }
}
  • use smartmatch experimental feature experimental features are introduced in Perl 5.10 version.

Enable feature using use experimental 'smartmatch'; statement ~~ in perl is a comparison and checks an element with iterated arrays.

use warnings;
use experimental 'smartmatch';


@numbers = (1, 2, 3,4,5,6);
my $searchElement=1;

if ($searchElement ~~ @numbers){
  print "Exists";
  
  } else {
    print "Not Exists";
}
  • use the grep function

The grep()function extracts an element from an array based on regular expression and checks for equality.

It satisfies the truthy condition if a value exists, else falsely conditoin

here is an example

@numbers = (1, 2, 3,4,5,6);
my $searchElement=1;

if ( grep( /^$$searchElement$/, @numbers ) ) {
  print "Exists";
  
  } else {
    print "Not Exists";
}

This takes more memory usage and should be avoided

  • use the CPAN module Another way, using install the CPAN module and use the any function.

This check whether any given element matches with an array of elements and return true or false

any(@array) eq 'element' checks whether an element exists in an array or not.

use this in conditional if to check boolean values.

Here is an example

use warnings;
use syntax 'junction';

@numbers = (1, 2, 3,4,5,6);
my $searchElement=1;

if ( any(@numbers) eq $searchElement )  {
  print "Exists";
  
  } else {
    print "Not Exists";
}

How do I check if an array contains a number?

To check if an array contains only scalar numbers, use the if conditional statement. use the grep function to check given element exists or not with the required regular expression. It returns true if an number scalar is found. else return false.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.