[Israel.pm] array 2 hash for quick search

Shlomi Fish shlomif at iglu.org.il
Tue Jun 15 02:35:17 PDT 2004


On Tuesday 15 June 2004 12:02, David Baird wrote:
> > Is there any other idiom for transforming an array to a hash
> > for quick search? I'm looking for some short hack.
> >
> > sub array2hash {
> > 	my ($array) = @_;
> > 	my %hash;
> > 	foreach my $array_item (@$array) {
> > 		$hash{$array_item}++
> > 	}
> > 	return \%hash;
> > }
>
> What about:
>
> %hash = map { $_, 1 } @array;
>

I'm not sure, but I think:

%hash=();
@hash{@array} = ((1) x @array);

would execute faster.

Note that if there are duplicate elements in the array, the behaviour will not 
be entirely identical to the code snippet Shlomo demonstrated.

Regards,

	Shlomi Fish

-- 

---------------------------------------------------------------------
Shlomi Fish      shlomif at iglu.org.il
Homepage:        http://shlomif.il.eu.org/

Quidquid latine dictum sit, altum viditur.
        [Whatever is said in Latin sounds profound.]



More information about the Perl mailing list