[Israel.pm] array 2 hash for quick search

Yuval Yaari yuval at windax.com
Tue Jun 15 04:38:25 PDT 2004


On Tue, 2004-06-15 at 15:22, Offer Kaye wrote:
> The difference between them is that (1) fills the values with the number 1,
> while (2) fills the values with the number of times a key appeared. (1) is
> also more elegant :-)
> Here are two other possible approaches:
> 
> 3)   my %hash = (@array,reverse @array);
> 4)   my %hash; @hash{@array} = (1) x ($#array+1);
> 
> Number (3) works since first @array[0,2,4,...] fills the keys of %hash, then
> the reversed array makes sure that @array[1,3,5,...] also fill the keys. The
> values will be the array values rather than a number, but the value was not
> specified by Shlomo as a requirement...
> Number (4) is not as elegent, IMHO, as the others, I've added it just for
> completeness. I also suspect it may be a little faster than (1) or (2) in
> filling up a hash when the array is large, but I'm not sure.
> 
> I'm curious - can anybody think of additional inventive ways to do this? :-)

I always use #4, and IIRC I picked it up from perldoc -q unique.
Or something alike.
Oh, I use scalar(@array) not $#array+1.

If anyone benchmarks these, I'd like to have the results.

  --Yuval




More information about the Perl mailing list