http://www.perlmonks.org?node_id=443731


in reply to What defines the choice of a Hash or an Array?

Hi ghenry,

When I am thinking of my code, there are two words which I look out for which suggest I might want ot use a hash. Those words are "of" and "contains" (or its more perlish alternative, exists).

An example of "of" might be

my %capitals = (France => "Paris", Scotland => "Edinburgh", ); # find the capital "of" Scotland print $capitals{"Scotland"}, "\n";

The fast access speed of hashes makes it a good candidate to find the intersection of two lists. For (a rather contrived) example

# we have a pre-prepared list of prime numbers my @primeslist = qw(2 3 5 7 11 13 17 19 23 29); # populate a hash with the primes as keys # this allows for fast retrieval my %primes; @primes{@primeslist} = (); # now we can loop through our new list ( 1 .. 30) # using the exists() function to (quickly) check if a key exists print "$_ is prime\n" for grep exists $primes{$_}, 1 .. 30;

Hope this helps

thinker

Replies are listed 'Best First'.
Re^2: What defines the choice of a Hash or an Array?
by ghenry (Vicar) on Mar 31, 2005 at 09:08 UTC

    Thanks thinker.

    Walking the road to enlightenment... I found a penguin and a camel on the way..... Fancy a yourname@perl.me.uk? Just ask!!!