Perlfunc: in_array()

If you need to determine if an array contains a specific element you can use this function:

sub in_array {
    my ($needle, @haystack) = @_;

    foreach my $l (@haystack) {
        if ($l eq $needle) { return 1; }
    }

    return 0;
}

Alternately you can use grep which in some cases can be faster:

sub in_array {
    my ($needle, @haystack) = @_;

    my $ret = grep { $_ eq $needle; } @haystack;

    return $ret;
}

Note: If you want to check integers just change the eq to ==



Note: Replies will be formatted with PHP Markdown Extra syntax.

Name: Email (Not Required):
 
Logged IP: 3.142.171.100
To prevent spam please submit by clicking the kitten: