[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Omaha.pm] map: make a hash from an array



On Sep 14, 2005, at 1:55 PM, Andy Lester wrote:
On Wed, Sep 14, 2005 at 09:46:28AM -0500, Jay Hannah (jhannah@omnihotels.com) wrote:
Here's a faster way:

my %keepthese = map { $_, 1 } @keepthese;

If you only care about the existence of a given element, and don't care
if it gets a value, you can assign to a hash slice:

    my %hash;
    @hash{@keepthese} = ();

If you need them to have a value, you can do this:

    my %hash;
    @hash{@keepthese} = (1) x @keepthese;

I've never used hash slices... I'll have to do some reading.

Finally, if you're just checking for existence, and don't really need
to worry about speed, you can do

    my $exists = grep { $_ eq $searching_for }, @keepthese;

Usually when I'm building a hash from an array I'm doing it for the sake of speed. My theory is that when I have unique keys building and then performing multiple lookups against a large hash is faster than performing multiple greps against a large array.

I use grep when I'm only doing 1 or 2 lookups against an array. My theory there being that its more efficient to do that than to build a hash that's only going to be used once.

(You need to remove the "," from your grep statement, btw. It's a syntax error.)

Thanks!

j