in reply to Hash Variable
in perl programs there are three ways to store the data you want to throw around, scalars, arrays and hashes. scalars, as you know by now, are the simplest. you put something in and you take it out in the same form. basically it just holds what you put in there. an array will take a whole bunch of things and order them for you. you give it a list and it will hole all the elements and give you whichever you want when you ask for it. if you want the 3rd item you placed in you simple ask for the item which is associated with the index [2](because the first is always 0!), and you will get it.
a hash is something you can think of as an array with a few different features. in fact, another name for a hash is an associative array. basically it is an unordered array which associates it's elements with names instead of numbers. above we said we ask for elements from an array with their associated numbers or indexes. with a hash, you would ask for things by their name, called a "key". i also said that a hash is unordered. this means that unlike an array it does not keep things in the order in which you put them in. perl decides what order to keep thing in according to black magic in the guts which optimizes the storage and retrieval of the data in the hash. let's look at some simple stuff to illustrate this.
first of all, proving how like an array a hash is, you can form one just like you would an array:
@array = ( one, monkey, two, donkey, three, funky ); # makes an array %hash = ( one, monkey, two, donkey, three, funky ); # makes a hash where each of one, two and three is a key # for the data to their right, but better written as %hash = ( one => monkey, two => donkey, three => funky ); # in both ones, two, three are keys and the rest the values. # the *only* difference is that the second is clearer for a # human. => has no special meaning at all - just another # comma for all perl cares. print $array[1]; # will print monkey print $hash{one}; # also prints monkey # notice both have stored simple scalers # so when we get the info for the print # we ask for a scalar.
what you store in a has doesn't have to be a scalar. you can store whole arrays, through references (another one I struggled with), and even other hashes.
I hope you find this useful. I also hope you don't see it as me talking down to you in any way. I struggled with this really hard a year ago. with no math or comp sci background all the references I found were leaving me spinning. i just hope to help you avoid that =)
"A man's maturity -- consists in having found again the seriousness one had as a child, at play." --Nietzsche
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re (tilly) 2: Hash Variable
by tilly (Archbishop) on Apr 06, 2001 at 13:48 UTC |