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 40
the cost of a banana is 10
the cost of a cherry is 20
To 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);
This means that 'mango' is related to 40, 'banana' to 10 and 'cherry' to 20.
%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:
%fruit = ('mango'=>40,'banana'=>10,'cherry'=>20);
print $fruit{'mango'},"\n";
print $fruit{'banana'},"\n";
10
Here, 'mango', 'banana', etc are called keys.
40, 10 and 20 are values.
Let's see one more example of hash containing elements of different types.
%a = ('y'=>"Hello World",'z'=>4);
$a{'x'} = 10;
print "$a{'x'}\n$a{'y'}\n$a{'z'}\n";
Hello World
4
Here, 'x', 'y' and 'z' are the keys and thier values are 10, "Hello World" and 4 respectively.
We can also change a value corresponding to a key. An example on this is given below.
%a = ('x'=>10,'y'=>"Hello World",'z'=>4);
$a{'x'} = "Hello";
print "$a{'x'}\n";
So we saw that $a{'x'}="Hello" changed the value of the key 'x' in the hash 'a' to "Hello".
keys and values
We can get all the keys of a hash in an array by using keys(%hash_name). Let's see an example of this:
%a = ('x'=>"Hello",'y'=>"Hello World",'z'=>4);
# using foreach
foreach $i (keys(%a)){
print "$i : ";
print "$a{$i}\n";
}
x : Hello
z : 4
Similarly, we can also get all the values of a hash in an array by using values(%hash_name). Look at the following example:
%a = ('x'=>"Hello",'y'=>"Hello World",'z'=>4);
# using foreach
foreach $i (values(%a)){
print "$i\n";
}
Hello World
Hello
exists
exists is used to check if a key is present in a hash or not. Its syntax is exists($hash_name{$key}). It returns a Boolean value corresponding to the existence of the key.
%a = ('x'=>1,'y'=>2,'z'=>3);
if(exists($a{'b'})){
print "a is present\n";
}
else{
print "Not present\n";
}
delete
delete is used to delete a key from a hash. Let's have a look at an example to see this working:
%a = ('x'=>1,'y'=>2,'z'=>3);
delete($a{'x'});
if(exists($a{'x'})){
print "x is not deleted\n";
}
else{
print "x is deleted\n";
}
Slicing
We can also slice a hash as we had done with an array. We extract an array of values from a hash. We use @ before a hash to do this. Let's see an example for this:
%a = ('x'=>1,'y'=>2,'z'=>3);
@b = @a{'x', 'y'};
print "@b\n";