[prog] list membership in Python and Perl

Caroline Johnston johnston at biochemistry.ucl.ac.uk
Wed May 11 02:34:22 EST 2005


I don't think there's an exact equivalent in perl, but maybe grep?

@matched = grep {/some_regex/} @an_array;

just evaluates the code between the curly brackets for each member of
@an_array in turn and @matched contains all the elements of @an_array for
which the code evaluated to true. The code doesn't have to be regex, it
could be something like:

@res = grep {$_->name eq 'herbert'} @an_array;

and @res will contain only those members of @an_array whose name method
returns 'herbert' (barring any stupid syntax errors on my part - I
haven't tested this ;).

I think if you're looking up values in an array a lot, then generally its
quicker and simpler to use a hash instead.

Is that any help?

Cxx


On Tue, 10 May 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.
>
> --
> Katie Bechtold         http://katie-and-rob.org/
>
>
> _______________________________________________
> Programming mailing list
> Programming at linuxchix.org
> http://mailman.linuxchix.org/mailman/listinfo/programming
>





More information about the Programming mailing list