Search code examples
perl

Is there a perl "not in" operator?


Suppose I have an array of numbers and I want to ensure that all of these fall within one of the set (x,y,z), I'm currently checking that the following evaluates to 0 :

scalar ( grep { $_ ne x && $_ ne y && $_ ne z } @arr )

Was just wondering if it'll not be easier if we had "IN" and "NOT IN" sql-like operators in perl too..

scalar ( grep { $_ NOT IN (x,y,z) } @arr )

Or is there one already?


Solution

  • A typical way to solve this is to use a hash:

    my %set = map {$_ => 1} qw( x y z ); # add x, y and z to the hash as keys
                                         # each with a value of 1
    
    my @not_in_set = grep {not $set{$_}} @arr;