Perl: find the index of an array item

I needed to find the index of an item in an array so I wrote a simple Perl function.

my @arr = qw(foo bar baz donk);
my $x   = array_index("bar", @arr)); # 1
sub array_index {
    my ($needle, @haystack) = @_;

    if (defined($needle)) {
        for (my $idx = 0; $idx < @haystack; $idx++) {
            if ($haystack[$idx] eq $needle) {
                return $idx;
            }
        }
    }

    return undef;
}
Leave A Reply - 1 Reply
Replies
Steven Haryanto 2013-10-18 03:26am - stevenharyanto@... - Logged IP: 203.130.198.32

Take a look at List::MoreUtils firstidx().

All content licensed under the Creative Commons License