Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
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
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 about the Monastery: (6)
As of 2014-08-23 15:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (174 votes), past polls