One of the strengths of PHP when it comes to arrays is considered to be the in_array function (http://php.net/in_array), this function takes two parameters; the array and the item to be searched in the array and then returns a boolean result whether the item exists in the array. Perl inherently lacks this functionality, even popular Perl modules like List::Util lack such a function/method.
As it was said by Plato once, “Necessity… the mother of invention.”, I required to check whether a name existed in an array, bored by using conventional method of iterating the array every time I need to check, I wrote a simple sub-routine to get the job done.
This sub-routine take two arguments, a reference to the array to be searched, and the item that needs to be searched. Simple enough the sub-routine works like magic, even my friend have found it very useful. I thought may be someone might find it useful, here’s it, take a look.
sub in_array
{
my ($arr,$search_for) = @_;
my %items = map {$_ => 1} @$arr; # create a hash out of the array values
return (exists($items{$search_for}))?1:0;
}
Sample Usage
my @arr = ('Manu','Pradeep','Shency','Shabbir');
sub in_array
{
my ($arr,$search_for) = @_;
my %items = map {$_ => 1} @$arr;
return (exists($items{$search_for}))?1:0;
}
if(in_array(\@arr,'Manu '))
{
print "Hurray! Manu you are in!!\n";
}
else
{
print "Ooops! Amlan you are out!!\n";
}
Output :
Hurray! Manu you are in!!