in reply to Determing the indice of an array

One further thought. If you really do need to look up an array index from its value using a reverse lookup hash, then it might be better to use the address of the array element rather than the element itself as the hash key, which neatly avoids the problem of duplicates.

my @a = ('a'..'d','a'..'d') print @a; a b c d a b c d my %a; @a{\(@a)} = 0..$#a; print %a; SCALAR(0x1bd5220) 2 SCALAR(0x1bd5208) 7 SCALAR(0x1bd299c) 5 SCALAR(0x1 +bdf15c) 1 SCALAR(0x1bd5268) 6 SCALAR(0x1bd52c8) 0 SCALAR(0x1bd53b8) 3 SCALAR(0x1 +bd2984) 4 for (@a) { print "$_ has an index of $a{\$_}\n"; } a has an index of 0 b has an index of 1 c has an index of 2 d has an index of 3 a has an index of 4 b has an index of 5 c has an index of 6 d has an index of 7

Examine what is said, not who speaks.
1) When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong.
2) The only way of discovering the limits of the possible is to venture a little way past them into the impossible
3) Any sufficiently advanced technology is indistinguishable from magic.
Arthur C. Clarke.

Replies are listed 'Best First'.
Re: Re: Determing the indice of an array
by Dr. Mu (Hermit) on Mar 11, 2003 at 04:42 UTC
    That's fine if you're actually using elements of @a for the lookup, but that rather presupposes that you know where they are to begin with, doesn't it? How about this case?
    my @a = ('a'..'d','a'..'d'); my %a; @a{\(@a)} = 0..$#a; my $x = 'b'; print "$x has an index of $a{\$x}\n"; b has an index of
    Better for the most general case would be to make a lookup hash keyed by the values of the array, with each value of the hash being a reference to an array to which you push the indices from the original array. That way, when you key the hash with an array value, you get every location in the array where that value occurred.