in reply to boolean IN(); function in perl like

There are several ways to do this. One of the easiest is grep:

if (grep {$_ eq $e} @a) { # $e is in @a }

However, if this is done many times and/or if @a gets to be too large, a hash lookup can be useful:

my %lookup = map { $_ => 1 } @a; # only do this once if you can if (exists $lookup{$e}) { # $e is in @a }

Cheers,
Ovid

New address of my CGI Course.

Replies are listed 'Best First'.
Re^2: boolean IN(); function in perl like
by nobull (Friar) on Jan 15, 2005 at 11:03 UTC
    my %lookup = map { $_ => 1 } @a;

    There is no need to put values in the hash.

    my %lookup; @lookup{@a}=();

    Futhermode if @a is holding a set of data that is not conceptually ordered it is better to simply use a hash and not an array in the first place.

Re^2: boolean IN(); function in perl like
by RhetTbull (Curate) on Jan 15, 2005 at 18:51 UTC
    One word of caution when using grep -- it will find all occurrences of $e in @a so if @a is large or there are a lot of occurrences of $e it will take longer than just looking for the first occurrence. You might also want to look at the any function in List::MoreUtils.