Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Re: why use a hash instead of an array

by space_monk (Chaplain)
on Jun 11, 2013 at 18:53 UTC ( #1038323=note: print w/replies, xml ) Need Help??

in reply to why use a hash instead of an array

i tried using variables set to numbers to get values out of arrays and it seemed to work. is that different from hashes?
Yes :-). A longer answer is that hashes use variables set to almost anything you like to set or get values in something that is a bit like an array.

and i would think the program would find the values faster if the keys are ordered like the indices in arrays.
The way values are stored in hashes is in a sort of order.

Whilst hashing implementations vary, what normally happens is that a hashing function translates the key into an index element which refers you to a bucket, which is a short list of possible matches. A hash is often (but not always) faster than an array because you do not have to search through all the elements to find what you are looking for - you only have to check a few elements, and often only one if the hashing function is effective. Hashes are actually (sort of) an array, and what is hidden from you is how the "key" is translated into an "index" into that array.

Most of your questions are answered by Googling for hashes and looking for the explanations. This article is a bit dated but provides a good starting point. At the end of the article are a series of book references - if you are seriously interested in programming you should certainly get hold of the Donald Knuth book(s) temporarily or permanently, as he is the father of a huge number of computer algorithms and methods that are still in use today.

Hashes are used for much more than trivial lookups. Another article shows that hashes can be used imaginatively for lots of different purposes. Searching through some PerlMonks answers will also reveal just how useful hashing can be when used in a creative {and in certain PerlMonks answers, some would say nefarious :-)} fashion.

If you spot any bugs in my solutions, it's because I've deliberately left them in as an exercise for the reader! :-)

Replies are listed 'Best First'.
Re^2: why use a hash instead of an array
by DarrenSol (Acolyte) on Jun 13, 2013 at 14:58 UTC
    thanks for the advice, and the link. looks like a good source of reading material to get my head in a programming mode.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1038323]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (3)
As of 2018-03-24 22:34 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (299 votes). Check out past polls.