in reply to Determing the indice of an array

Yet another way to do this, without creating a hash lookup would be to just go through each and keep track of what index your on when you find what you are looking for.
May be better suited if you are dealing with very large arrays.
#!/usr/local/bin/perl5.6.0 use strict; my $index_of_item; my $item = q{d}; for ( qw| a b c d e f g | ) { ( $_ eq $item ) ? last : $index_of_item++; } print qq{Index of [$item] is [$index_of_item]\n};

Wonko

Replies are listed 'Best First'.
Re: Re: Determing the indice of an array
by rjray (Chaplain) on Mar 10, 2003 at 22:58 UTC

    A little heavy. For one thing, it seems safe to assume that they are searching an array, not a constant list. Thus, you don't really need the trinary operator:

    my @ary = (...); my $index; for $index (0 .. $#ary) { last if $ary[$index] eq $val; } print "Index = $index\n";

    (Handling the case of no match is left as an exercise to the reader. Because I'm lazy today.)

    As others have pointed out, conversion to a hash has a lot of drawbacks, not the least of which being the duplicate-value problem and the fact that it just isn't as efficient as travelling the array like above. Converting to a hash is still going to walk the array.

    --rjray