Perl Programming/Hash variables

A Perl hash is similar to an ordinary array, but instead of using integer indexes, a hash uses "keys" that can take on any scalar value. These are usually strings or numbers.

Syntax: instead of the  operator, associative arrays use the   symbol, and rather than square brackets , as in  , hash elements are referenced using curly brackets  , as in.

Hashes are one of the most powerful and commonly used features in Perl. A typical use would be to build a hash that contains a "dictionary", with each key being a word in the dictionary, and the corresponding values being the definitions of those words.

A hash containing the sounds various household pets make is below

'=>' and ',' are actually interchangeable, so the right side could look exactly like an array. This means that you can assign an array to a hash. In such an assignment, each element with an even index (starting from 0) in the array becomes a key in the hash. The following statements create the same hash as the previous one does But the first style is more preferred because it makes the statement more readable.

To access a hash element, use the curly brackets: will print the following to STDOUT

The cat goes meow.

To add a new sound item to a hash To overwrite an existing element, just reassign it To remove an item from a hash, use delete. Setting the value to undef does not delete the item; using exists on a key that has been set to undef will still return true.

"Associative Arrays"
Originally, a "hash" was called an "associative array", but this term is a bit outdated (people just got sick and tired of using seven syllables). Although it isn't intuitive for newcomers to programming, "hash" is now the preferred term. The name is derived from the computer science term, hashtable.

Printing hash contents
If you know PHP, you may have thought by now of some convenient way to print the contents of your array the way  does...

Counting the number of entries in a hash
To get the size of the hash, simply find the size of the result of the  function, by evaluating it in scalar context:

Hash of Hashes of Hashes
You can define multidimensional hash array variables. An example may look like this:

This code will produce:

1      a       A       FIRST 1      b       C       SECOND 1      c       B       THIRD $VAR1 = { '1' => {                    'c' => { 'B' => 'THIRD' },                    'a' => { 'A' => 'FIRST' },                    'b' => { 'C' => 'SECOND' }                  }          };