Search code examples
perlarrayscomparison

How can I check if a Perl array contains a particular value?


I am trying to figure out a way of checking for the existence of a value in an array without iterating through the array.

I am reading a file for a parameter. I have a long list of parameters I do not want to deal with. I placed these unwanted parameters in an array @badparams.

I want to read a new parameter and if it does not exist in @badparams, process it. If it does exist in @badparams, go to the next read.


Solution

  • 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;