in reply to better way to find list members?

This is from Perlfaq.com.

@animals = qw(cat dog bat rat gerbil snake pig chicken); foreach (@animals) { $animals{$_}++; } # initialize %animals hash # use a hash if (exists $animals{'pig'}) { print "We have a pig!\n"; } # use grep if (grep { $_ eq 'snake'} @animals) { print "We have a snake!\n"; } # use a for loop for (@animals) { last if $_ eq 'dog'; } print "We have a dog!\n";

Cheers,
KM

Replies are listed 'Best First'.
RE: Re: better way to find list members?
by DrManhattan (Chaplain) on Oct 18, 2000 at 03:35 UTC
    foreach (@animals) { $animals{$_}++; } # initialize %animals hash
    Here's a faster way to do that (looks neat too):
    @animals{@animals} = (1) x @animals;
    It's not exactly the same since it's setting each hash member to 1 instead of ++'ing it, but that's no big deal if you're just checking for an element's existance.

    -Matt

      If all you want is existence, then this:
      @animals{@animals}=undef; print "Got a dog!\n" if exists $animals{dog};
      is faster and uses less memory.

      Are you sure you meant to do @animals{@animals}? That code seems fraught with peril...

      Update: Actually, the more I look at it, the more it's starting to possibly make some sense to me...

RE: Re: better way to find list members?
by runrig (Abbot) on Oct 18, 2000 at 03:56 UTC
    foreach (@animals) { $animals{$_}++; } # initialize %animals hash # could be $animals{$_}++ for @animals;
    Regarding:
    # use a for loop for (@animals) { last if $_ eq 'dog'; } print "We have a dog!\n";
    That'll always print 'We have a dog!', even when we don't.