[prog] list membership in Python and Perl
Jacinta Richardson
jarich at perltraining.com.au
Wed May 11 09:58:50 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.
Perl has a module for everything. Even writing Python (Inline::Python). The
module which does membership is imaginatively called List::Member
use List::Member;
my $target = 'bar';
my @look_in = ('foo','baz','bar','etc');
if( member($target, @look_in) + 1) {
print "It's a member of the array\n";
}
It returns the index of the array in which the element exists, or -1. This is
why we add 1 for a conditional test. Otherwise if it existed in the first index
we'd return 0 (false).
Having said that, this module is rarely used (in my experience). You're much
more likely to see code as follows:
# is $target in @list?
if( grep /^$target$/, @list ) {
print "It's a member of the array\n";
}
or more likely (it's faster):
# explicit quoting makes it works with numbers and strings
if( grep { "$_" eq "$target" } @list ) {
print "It's a member of the array\n";
}
If more than one of these tests are likely you'll usually see something like:
# Go through each target and report whether it's in the list
my @targets = qw/1 2 3 4 5/;
my @list = qw/4 5 6 7 8 9 0 1/;
# Create hash and populate with elements from @list
my %unique;
@unique{ @list } = (); # hash slice
foreach my $target (@targets) {
if( exists $unique{$target } ) {
print "It's a member of the array\n";
}
}
Perl doesn't have the syntatic sugar that Python provides for this particular
case.
All the best,
Jacinta
--
("`-''-/").___..--''"`-._ | Jacinta Richardson |
`6_ 6 ) `-. ( ).`-.__.`) | Perl Training Australia |
(_Y_.)' ._ ) `._ `. ``-..-' | +61 3 9354 6001 |
_..`--'_..-_/ /--'_.' ,' | contact at perltraining.com.au |
(il),-'' (li),' ((!.-' | www.perltraining.com.au |
More information about the Programming
mailing list