bengmau has asked for the wisdom of the Perl Monks concerning the following question:

Having a brain fart.. I want to check if a number is in an array or list of numbers.
@array = (10,11,12,13,14,20,21,25); $x=1 if (grep /$x/,@array) { ... }
This won't work since 10,11,21 all have 1 in it.. I did some searching on this... can I do this?
if (grep($_=$x, @array)) { }

Replies are listed 'Best First'.
Re: check if a number is in a list
by crashtest (Curate) on Jun 26, 2005 at 02:36 UTC
    You almost got it. Use "==" (not "=") for number comparisons:
    if (grep $_ == $x, @array) { print "Found $x in the array!\n"; }
    ... or, if you like the regular expression, just anchor it:
    if (grep /^$x$/, @array){ ... }

Re: check if a number is in a list
by runrig (Abbot) on Jun 26, 2005 at 02:38 UTC
    You want '==' there. You might want to store the values as keys in a hash though (update: as davidrw demonstrates below -- do it that way if you're doing many checks on the same list) to make it simple, or do something like:
    my @array = qw(1 2 3); my $x = 1; if (num_in($x, @array)) { ... } sub num_in { my $num = shift; $_ == $num and return 1 for @_; return; }
      (for OP's benefit) the hash method:
      my @array = (10,11,12,13,14,20,21,25); my $x = 1; my %array = map { $_ => undef } @array; if( exists $array{$x} ){ ... }
        Is the map really needed? What about:
        my %array; @array{@array}=();
        No, the map isn't really needed, and might cause confusion, but if it does, I'd bet the @array{@array}=(); idiom isn't going to be understood either.

        OP, in both cases above, the idea is to have the numbers in your list to actually be in a hash rather than an array. The map and @array{@array} thing are simply shorthand ways to take your existing array and make it into a hash.

        Depending on your actual implementation, you might be better off if you created and added/removed the numbers meant to be within the list, and did so using hash operations instead. Then you wouldn't need the shorthand idioms above.

        -Scott

Re: check if a number is in a list
by neniro (Priest) on Jun 26, 2005 at 10:00 UTC
    You can also use Perl6::Junction for a more "natural" way:
    use Perl6::Junction qw/any/; if (any(@list_of_values) == $value) { ... }