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

How do you test to see if $test equals any item in an array? How would I go about this? I need to iterate over everything in the array and see if $test equals any one of them.
unless ( $test eq @array)

Replies are listed 'Best First'.
Re: testing against an array
by ccn (Vicar) on Apr 03, 2004 at 20:31 UTC
    There are two ways
    1. simple
    if( grep{$test eq $_} @array ){ # }
    2. fast
    foreach (@array) { next unless $_ eq $test; #here is a match # ... last; }
    You can use '==' instead of 'eq' if the elements are numeric
    Update: The third way can be useful if a great number of testing needed
    my %test @test{@array} = (); foreach (@many_test_values) { if (exists $test{$_}) { # here is a match } }
Re: testing against an array
by dragonchild (Archbishop) on Apr 03, 2004 at 21:29 UTC
    Use Quantum::Superpositions.
    unless ($test eq any(@array))

    ------
    We are the carpenters and bricklayers of the Information Age.

    Then there are Damian modules.... *sigh* ... that's not about being less-lazy -- that's about being on some really good drugs -- you know, there is no spoon. - flyingmoose

Re: testing against an array
by McMahon (Chaplain) on Apr 03, 2004 at 20:19 UTC
    How about this:
    foreach my $item(@array) { if ($test eq $item) { #do something interesting } }
    Hope that helps....
      Even shorter:

      if (grep { /^$testforthis$/ } @array { #do something }
      See grep for more information.
        Even though the person below me already mentioned this, I felt it needed point out again: You can use any expression with grep, not just a regular expression, so if your testing for equality, use the equality test operator, don't try to coerce a regex in to pretending to be one.

        if( grep $test eq $_, @array )
        A reply falls below the community's threshold of quality. You may see it by logging in.
Re: testing against an array
by muba (Priest) on Apr 03, 2004 at 20:49 UTC
    or... 'how to loop over an array while checking it's elements in the shortest possible way' :)
    'Short' either meaning 'the least keystrokes' or 'the shortest execution time of the code'
Re: testing against an array
by matija (Priest) on Apr 03, 2004 at 20:36 UTC
    how about
    my $ok=0; map ($_ eq $test?($ok=1):0,@array); unless ($ok) {....