Hashes are group of key-value pairs. Hash variables are prefixed with “%” sign. Lets take a simple example first then we will discuss the hash in detail.
#!/usr/bin/perl %age = ('Chaitanya Singh', 29, 'Ajeet', 28, 'Lisa', 25); print "\$age{'Lisa'}: $age{'Lisa'}\n"; print "\$age{'Chaitanya Singh'}: $age{'Chaitanya Singh'}\n"; print "\$age{'Ajeet'}: $age{'Ajeet'}\n";
Output:
$age{'Lisa'}: 25 $age{'Chaitanya Singh'}: 29 $age{'Ajeet'}: 28
In the above example, we have created a hash and displayed its elements. Lets see each part in detail:
Creating a hash
First method: This is what we have seen in the example above –
%age = ('Chaitanya Singh', 29, 'Ajeet', 28, 'Lisa', 25);
Here ‘Chaitanya Singh’ is the key 1 and 29 is value 1
‘Ajeet’ is key 2 and 28 is value 2
similarly ‘Lisa’ and 25 is third key-value pair.
Second method: This is the preferred way of creating a hash as it improves the readability. In this method we seperate key and value of each pair with ‘=>’ symbol.
For example:
%age = ('Chaitanya Singh' => 29, 'Ajeet' => 28, 'Lisa' => 25);
Useful Hash functions:
1) keys function:
keys function returns the list of all the keys in a hash.
Example:
#!/usr/bin/perl %age = ('Chaitanya Singh' => 29, 'Ajeet' => 28, 'Lisa' => 25); my @k = keys %age; print "Keys: @k\n";
Output:
Keys: Ajeet Chaitanya Singh Lisa
2) values function:
values function returns the list of all the values in a hash.
Example:
#!/usr/bin/perl %age = ('Chaitanya Singh' => 29, 'Ajeet' => 28, 'Lisa' => 25); my @k = values %age; print "Values: @k\n";
Output:
Values: 28 29 25
3) each function:
each function is used for iterating over a hash, it is generally used in while loop.
Example:
#!/usr/bin/perl %age = ('Chaitanya Singh' => 29, 'Ajeet' => 28, 'Lisa' => 25); while ( ($key, $value) = each %age ) { print "Key: $key, Value: $value\n"; }
Output:
Key: Lisa, Value: 25 Key: Chaitanya Singh, Value: 29 Key: Ajeet, Value: 28
Leave a Reply