Quick tip: Perl version of PHP’s in_array()

There are a million and one ways to do this in Perl, sick but here’s a fairly readable way that you can copy/paste into your Perl scripts:


####
# From http://www.seancolombo.com
# Equivalent to PHP's in_array.  If the first element is in the array
# passed in as the second parameter, then the sub-routine returns non-zero.
# If the element is not in the array, then the sub-routine returns zero.
####
sub in_array{
my $retVal = 0;
my $val = shift(@_);
foreach my $curr (@_){
if($curr eq $val){
$retVal = 1;
last;
}
}
return $retVal;
} # end in_array()

Example usage:


if(in_array($needle, @haystack)){
print "Found it!
";
}

Been using this for years & it’s made my life a bit easier. Hope that’s useful to someone!