Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

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

thinker


Comment on Re: What defines the choice of a Hash or an Array?
Select or Download Code
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!!!

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (14)
As of 2015-07-31 12:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (277 votes), past polls