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

Is there a simple way to see if an element exists in a list? Right now I use this code which seems cumbersome:
sub IsItem { # usage: IsItem(item to find, pointer to list to search) my $ref = @_[1]; foreach my $e (@{$ref}) { if (@_[0] eq $e) {return 1} } return 0; } my @a = (10,20,30); print 'IsItem=',IsItem(20,\@a); print 'IsItem=',IsItem(5,\@a);

Replies are listed 'Best First'.
Re: Determining if an element in a list
by runrig (Abbot) on Sep 13, 2001 at 01:37 UTC
Re: Determining if an element in a list
by shadox (Priest) on Sep 13, 2001 at 01:51 UTC
    Use the grep function, it searches for a pattern in a @list.
    use warnings; use strict; my $pattern = '1'; my @list = ( 1,2,'a','b',5,1,1,'t'); # In a scalar context grep will return the total times # that the +pattern was find in @list # If you use @times = grep(/$pattern/,@list); # @times will contain the pattern it founds in the array # in this case @times will be ( 1 , 1 , 1 ) my $times = grep(/$pattern/,@list); print "The pattern was found $times times";

      In general, this is a pretty inefficient solution as you're searching the whole list every time. In the worst case you have a very long list and the element you're searching for is the first element.

      Something like thoe following is better:

      my $found; foreach (@list) { if (/$pattern/) { $found = 1; last; } }

      But the solutions in the FAQ are even better.

      --
      <http://www.dave.org.uk>

      Perl Training in the UK <http://www.iterative-software.com>

Re: Determining if an element in a list
by jmcnamara (Monsignor) on Sep 13, 2001 at 03:16 UTC

    I'm posting the following alternative mainly as a diversion. The information in perlfaq4 will point you in the right direction, as runrig suggested.

    The function takes an array as an argument rather than an array ref. Definitely not for production code. ;-)</t>
    #!/usr/bin/perl -w use strict; my @a = (10, 20, 30); my @b = (11, 20, 30); sub item_exists { @_{@_} = 1; $_{$_[0]} ? 0:1; } print "10 ", item_exists(10, @a) ? "is ": "isn't", " in qw(@a).\n"; print "11 ", item_exists(11, @a) ? "is ": "isn't", " in qw(@a).\n"; print "10 ", item_exists(10, @b) ? "is ": "isn't", " in qw(@b).\n"; print "11 ", item_exists(11, @b) ? "is ": "isn't", " in qw(@b).\n";

    John.
    --