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 ==

Leave A Reply
All content licensed under the Creative Commons License