Search code examples
arraysperlvariableshashperl-data-structures

Perl: Searching for item in an Array


Given an array @A we want to check if the element $B is in it. One way is to say this:

Foreach $element (@A){
    if($element eq $B){
        print "$B is in array A";
    }
}

However when it gets to Perl, I am thinking always about the most elegant way. And this is what I am thinking: Is there a way to find out if array A contains B if we convert A to a variable string and use

index(@A,$B)=>0

Is that possible?


Solution

  • There are many ways to find out whether the element is present in the array or not:

    1. Using foreach

      foreach my $element (@a) {
          if($element eq $b) {
             # do something             
             last;
          }
      }
      
    2. Using Grep:

      my $found = grep { $_ eq $b } @a;
      
    3. Using List::Util module

      use List::Util qw(first); 
      
      my $found = first { $_ eq $b } @a;
      
    4. Using Hash initialised by a Slice

      my %check;
      @check{@a} = ();
      
      my $found = exists $check{$b};
      
    5. Using Hash initialised by map

      my %check = map { $_ => 1 } @a;
      
      my $found = $check{$b};