Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

Re: What defines the choice of a Hash or an Array?

by thinker (Parson)
on Mar 31, 2005 at 08:32 UTC ( #443731=note: print w/replies, xml ) Need Help??

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


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 Just ask!!!

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://443731]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (6)
As of 2021-09-27 14:49 GMT
Find Nodes?
    Voting Booth?

    No recent polls found