Hashes are an advanced form of array. One of the limitations of an array is that the information contained within it can be difficult to get to. For example, imagine that you have a list of people and their ages.
The hash solves this problem very neatly by allowing us to access that @ages array not by an index, but by a scalar key. For example to use age of different people we can use thier names as key to define a hash.

Creation of Hash

Hashes are created in one of two ways. In the first, you assign a value to a named key on a one-by-one basis:
In the second case, you use a list, which is converted by taking individual pairs from the list: the first element of the pair is used as the key, and the second, as the value. For example,
For clarity, you can use => as an alias for , to indicate the key/value pairs:

Extracting Individual Elements

You can extract individual elements from a hash by specifying the key for the value that you want within braces:

Extracting Slices

You can extract slices out of a hash just as you can extract slices from an array. You do, however, need to use the @ prefix because the return value will be a list of corresponding values:
Note: Using $hash{-Fred, -Barney} would return nothing.

Extracting Keys and Values

You can get a list of all of the keys from a hash by using keys
These can be useful in loops when you want to print all of the contents of a hash:
The problem with this approach is that (%ages) returns a list of values. So to resolve this problem we have each function which will retun us key and value pair as given below

Checking for Existence

If you try to access a key/value pair from a hash that doesn.t exist, you.ll normally get the undefined value, and if you have warnings switched on, then you.ll get a warning generated at run time. You can get around this by using the exists function, which returns true if the named key exists, irrespective of what its value might be:

Sorting/Ordering Hashes

There is no way to simply guarantee that the order in which a list of keys, values, or key/value pairs will always be the same. In fact, it’s best not even to rely on the order between two sequential evaluations:
If you want to guarantee the order, use sort, as, for example:
If you are accessing a hash a number of times and want to use the same order, consider creating a single array to hold the sorted sequence, and then use the array (which will remain in sorted order) to iterate over the hash. For example:

Hash Size

You get the size – that is, the number of elements – from a hash by using scalar context on either keys or values:

Add & Remove Elements in Hashes

Adding a new key/value pair can be done with one line of code using simple assignment operator. But to remove an element from the hash you need to use delete function.

What Do You Think on This ? Say Here

This site uses Akismet to reduce spam. Learn how your comment data is processed.