Perl: finding an element in an array

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

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

However, when it comes to Perl, I always think of the most elegant way. And this is what I’m thinking about: Is there a way to find out if the array contains AB, if we convert A to a variable string and use

index(@A,$B)=>0

Is it possible?

+3
source share
3 answers

There are many ways to find out if an element is present in an array or not:

  • Using foreach

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

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

    use List::Util qw(first); 
    
    my $found = first { $_ eq $b } @a;
    
  • Using a Slice Initialized Hash

    my %check;
    @check{@a} = ();
    
    my $found = exists $check{$b};
    
  • Using a Map Initialized Hash

    my %check = map { $_ => 1 } @a;
    
    my $found = $check{$b};
    
+13
source
use 5.10.1;

$B ~~ @A and say '$B in @A';
+6
use List::AllUtils qw/ any /;
print "\@A contains $B" if any { $B eq $_ } @A;
0

All Articles