| Lesson 6a - Hashes |
|
Summary: Sometimes storing
data in a sequential order isn't the best way to go about a task. Hashes
allow data to be stored by reference to 'keys', or strings associated
with those particular data. An examplary use of hashes would be storing
a list of characters associated with the name of a television series. Hashes are named beginning with the `%` character, like `%my_hash`. Initializing a hash is much like initializing an array, but rather than just providing a list of elements, one has to provide a 'key' for each element. The key must be followed by the data to be stored with that key. Example: ------------------------------------- When key/data combinations
are separated like this on separate lines, it's easy to tell them apart.
However, using commas like this can be confusing if working with arrays
at the same time, so `=>` can be used as a separator for keys and
data to make your code more readable. This example does exactly the
same thing:
Data in a hash is accessed like data in an array, however, curly brackets are used instead of square brackets and the key is substituted for the array subscript. Example: -------------------------------------
`keys` and `values`
return arrays containing, respectively, the keys and associated data
from the specified hash. They are sorted in an apparently random order,
but the order is the same for both functions. These functions are more
useful (for example) when working with for loops, which will be discussed
in the flow control section. Example:
The `%ENV` hash
contains the current shell environment, with each environment variable
being linked to a key with its name. In a CGI context, `%ENV` can be
used to retrieve things such as the query string (i.e. http://my.server.com/cgi-bin/script.cgi?this+is+the+query+string)
and other miscellaneous information. |