How can I check if a Perl array contains a particular value?
Simply turn the array into a hash:
my %params = map { $_ => 1 } @badparams;
if(exists($params{$someparam})) { ... }
You can also add more (unique) params to the list:
$params{$newparam} = 1;
And later get a list of (unique) params back:
@badparams = keys %params;
Best general purpose - Especially short arrays (1000 items or less) and coders that are unsure of what optimizations best suit their needs.
# $value can be any regex. be safe
if ( grep( /^$value$/, @array ) ) {
print "found it";
}
It has been mentioned that grep passes through all values even if the first value in the array matches. This is true, however grep is still extremely fast for most cases. If you're talking about short arrays (less than 1000 items) then most algorithms are going to be pretty fast anyway. If you're talking about very long arrays (1,000,000 items) grep is acceptably quick regardless of whether the item is the first or the middle or last in the array.
Optimization Cases for longer arrays:
If your array is sorted, use a "binary search".
If the same array is repeatedly searched many times, copy it into a hash first and then check the hash. If memory is a concern, then move each item from the array into the hash. More memory efficient but destroys the original array.
If same values are searched repeatedly within the array, lazily build a cache. (as each item is searched, first check if the search result was stored in a persisted hash. if the search result is not found in the hash, then search the array and put the result in the persisted hash so that next time we'll find it in the hash and skip the search).
Note: these optimizations will only be faster when dealing with long arrays. Don't over optimize.
You can use smartmatch feature in Perl 5.10 as follows:
For literal value lookup doing below will do the trick.
if ( "value" ~~ @array )
For scalar lookup, doing below will work as above.
if ($val ~~ @array)
For inline array doing below, will work as above.
if ( $var ~~ ['bar', 'value', 'foo'] )
In Perl 5.18 smartmatch is flagged as experimental therefore you need to turn off the warnings by turning on experimental pragma by adding below to your script/module:
use experimental 'smartmatch';
Alternatively if you want to avoid the use of smartmatch - then as Aaron said use:
if ( grep( /^$value$/, @array ) ) {
#TODO:
}