Perl: Searching for item in an Array
arrays, hash, perl, perl-data-structures, variables
Solution
There are many ways to find out whether the element is present in the 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 Hash initialised by a Slice
my %check;
@check{@a} = ();
my $found = exists $check{$b};
Using Hash initialised by map
my %check = map { $_ => 1 } @a;
my $found = $check{$b};
Problem
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?