What are hashes in Perl?
Hashes in Perl are key value pairs similar to dictionaries in Python. Hash variables can be defined as shown below, similar to how a variable named employees is defined. Each variable is preceded by a $ sign, and the data is stored within closed brackets (). Each element is separated by ,, but forms pairs of keys corresponding to values.
%employees = ('Samia', 10, 'Ali', 20, 'Sana', 30);print($employees{'Samia'})
How to define hashes
You can define hash variables as shown below. In the first method, one can simply list a key and its value alternately within () brackets to define the hash variable. Secondly, you can make use of the => arrows to show that one key belongs to another value. Finally, you can also use hyphens (-) to define a key element, but in this case, you must ensure that keys are one-worded.
%employees = ('Samia', 10, 'Ali', 20, 'Sana', 30);%employeesone = ('Samia' => 10, 'Ali' => 20, 'Sana' => 30);%employeestwo = (-Samia=> 10, -Ali=> 20, -Sana=>30);print($employees{'Samia'});print("\n");print($employeesone{'Samia'});print("\n");print($employeestwo{-Samia});
How to add/remove elements to hashes
You can add or remove elements from hashes as shown below. Adding an element is simple, as you can do so by using the {} brackets; however, deleting requires the use of the special keyword delete. You can observe that Samia has been deleted and Ali has been added.
%employees = ('Samia', 10, 'Sana', 30);$employees{'Ali'} = 20;delete $employees{'Samia'};print "$_ $h{$_}\n" for (keys %employees);
Size of hashes
You can deduce the size of hashes by storing all the keys in one variable and printing that variable’s scalar. $ helps us put all those keys into scalar context, which means that rather than getting the keys, we acquire the number of keys in a hash or the size of the hash.
%employees = ('Samia', 10, 'Sana', 30);@allkeys = keys % employees;$size = @allkeys;print($size);
Slicing hashes
To slice hashes, you can create arrays of your selected keys using the @ symbol; this slices the hashes into your desired keys.
%employees = ('Samia', 10, 'Sana', 30, 'ali', 20, 'Sania', '40');@array = @employees{'Samia', 'Sana'};print(@array);
Free Resources