Hashes in Perl

Hash is the most important data structure of Perl. In Python, it is known as dictionary. Like array, it is also used to store data but in a bit different and quite useful way. So, let's discuss about hashes.

Suppose, the cost of a mango is 40the cost of a banana is 10the cost of a cherry is 20To store them, we can use an array, but there is another way to store all these in a better way.We use $ for scalars,@ for array.Similarly, we use % for hash.Let's code using hash.

%fruit=('mango'=>40,'banana'=>10,'cherry'=>20);

Output

This means that 'mango' is related to 40, 'banana' to 10 and 'cherry' to 20.

%fruit = ('mango'=>40,'banana'=>10,'cherry'=>20) is same as%fruit = ('mango',40,'banana',10,'cherry',20) but the first one is a more clear way of representation.

We access the elements of an array 'a' with $a[0], $a[1] and so on. For dictionary, we do this: