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

What would be the quickest way to check if a scalar variable such as $scalar matches any one of the scalar values of an array such as @array ?

So, if   $scalar = 3 and   @array = [0, 1, 2, 3, 4, 5] , then it would return true.

Zenon Zabinski | zdog | zdog7@hotmail.com

Replies are listed 'Best First'.
Re: Comparing Scalars and Arrays
by btrott (Parson) on Jul 19, 2000 at 21:26 UTC
Re: Comparing Scalars and Arrays
by cwest (Friar) on Jul 19, 2000 at 21:27 UTC
    Grep comes to mind...
    y @array = ( 9, 2, 23, 24, 5, 6 ); my $scalar = 5; print "Got it\n" if grep /^$scalar$/, @array;
    also perlfaq4 should have this
    --
    Casey
    
RE: Comparing Scalars and Arrays
by autark (Friar) on Jul 19, 2000 at 21:31 UTC
    If it smells like grep and looks like grep, then it must be grep :-)
    if( grep { $scalar == $_ } @array ) { print "$scalar is member of @array\n"; } else { print "$scalar is not member of @array\n"; }
    I see that you in your question has assigned an anonymous array to @array, if that really is the case, then you have to do some more work:
    $scalar = 3; @array = ([1, 2], [3, 4, 5], [6, 7, 8 ,9]); if( grep { $scalar == $_ } map { @$_ } @array ) { print "Yes\n" } else { print "No\n" }
    Autark.
      IMHO, your second example is great, but the condition seems like it could be more readable. Since you use grep, why not use it again, instead of map
      grep { grep { $scalar == $_ } @{$_} } @array
      Just MHO...

      Update:And it's faster, 1000000 iterations has Grep+Grep at 11 Walclocks and Grep+Map at 16.

      --
      Casey
      
Re: Comparing Scalars and Arrays
by lhoward (Vicar) on Jul 19, 2000 at 21:29 UTC
    If this is a comparison you're goona do more than once then the best bet is to load the array into a hash as its keys and determine membership by looking for existance of the hash element.

    If this is something you need to do only once, then you're best off with something like this:

    my $elem_count=grep /^$scalar$/,@array;
RE: Comparing Scalars and Arrays
by Russ (Deacon) on Jul 19, 2000 at 22:38 UTC