[prog] list membership in Python and Perl

Douglas Hunter dug at plusthree.com
Wed May 11 09:58:10 EST 2005


Katie Bechtold wrote:
> In the course of learning Python, I've been introduced to a list
> operation that tests for list membership:
> 
> 
>>>>3 in [1, 2, 3]                    # Membership (1 means true)
> 
> 1
> 
> Is there any analogous list operation in Perl?  I haven't been able
> to find one, but it seems so useful and basic that I must be missing
> something.
> 

It seems that often times that function gets hand-rolled in Perl 
programs, via the grep or hash ways that other folks in this thread 
mentioned.

An alternative to the grep method is to short-circuit out of the loop as 
soon as you find your match, which I presume Python's 'in' does:

sub in {
   my $match = shift;
   foreach (@_) {
     return 1 if $_ eq $match;
   }
}

Instead of gathering all of the matches (as the grep does), this way 
returns as soon as it finds a match.

List::Util (which is a core module) provides a function called 'first' 
which is quite similar to the 'in' subroutine coded above, except like 
'grep' it takes a code block.

The equivalent to the example you used would look something like:

use List::Util 'first';
first { $_ == 3 } ( 1, 2, 3 );

This difference being that it would return the first value of the list 
that matched the code block, rather than 1.

-- Douglas


More information about the Programming mailing list