Perl - Creating a Hash from an Array
Last Updated :
02 Jul, 2020
Hashing is the process of converting a given key into another value. A
hash function is used to generate the new value (called hash) according to a mathematical algorithm.
A
Perl hash is defined by key-value pairs.
Perl stores elements of a hash in such an optimal way that you can look up its values based on keys very fast. Like a scalar or an array variable, a hash variable has its own prefix. A hash variable must begin with a
percent sign (%). A hash key must be unique. If you try to add a new key-value pair with the key that already exists, the value of the existing key will be over-written.
Example:
Perl
#!/usr/bin/perl
# defines a hash named subjects
# the first scalar inside the
# brackets are hashes and the
# second one beside them are values
my %subjects = qw(Physics Laws
Chemistry Exceptions
Mathematics Formulas
Programming Fun);
# getting the value of Programming
print($subjects{'Programming'});
To make code more elegant and easier to read, Perl provides the => operator. It helps differentiate between keys and values. The keys always points to their corresponding values with the => operator. However, here Perl requires the keys of a hash to be strings, meanwhile, the values can be any scalars. If you use non-string values as the keys, you may get an unexpected result. The $subjects hash can be rewritten using => operator as follows:
perl
#!/usr/bin/perl
# declaring hash using the => operator
my %subjects = ( Physics => 'Laws',
Chemistry => 'Exceptions',
Mathematics => 'Formulas',
Programming => 'Fun' );
# getting the value of Mathematics
print($subjects{'Mathematics'});
Odd number of elements in the hash assignment
When the number of elements in the hash assignment is odd, Perl gives us a warning as it notices that the number of elements being assigned to the hash cannot be divided by 2. That the number of elements is odd.
Since this is just a warning (and it is only displayed if 'use warnings' is in effect), the script will go on with the assignment. The odd elements ("Physics", "Chemistry", "Mathematics" and "Programming") will become keys and the even elements ("Laws", "Exceptions" and "Formulas") will become the values. Because the number of elements is odd, the last key ("Programming") will not have a pair.
perl
#!/usr/bin/perl
use warnings;
use strict;
# declaring hash with odd number
# of assignments
my %subjects = qw( Physics Laws
Chemistry Exceptions
Mathematics Formulas
Programming );
print "Physics = $subjects{'Physics'}\n";
print "Chemistry = $subjects{'Chemistry'}\n";
print "Mathematics = $subjects{'Mathematics'}\n";
print "Programming = $subjects{'Programming'}\n";
Output
Physics = Laws
Chemistry = Exceptions
Mathematics = Formulas
Programming =
Odd number of elements in hash assignment at line 7.
Use of uninitialized value $subjects{"Programming"} in print at line 12.
Adding, Removing and Modifying elements of a Hash
Adding new elements to the Hash and modifying them, are very similar to each other. The name of the hash is followed by the key enclosed within curly braces and assigned a value. We can use the delete function to remove a hash. Following sample code shows how to assign/modify and remove elements from a Hash:
perl
#!/usr/bin/perl
# declaring a hash
my %subjects = ( Physics => 'Laws',
Chemistry => 'Exceptions',
Mathematics => 'Formulas',
Programming => 'Fun' );
# extracting keys of hash in an array
@keys = keys %subjects;
# determining size of keys-array i.e.
# number of elements in hash
$size = @keys;
print "Hash size is $size\n";
# adding an element to the hash;
$subjects{'Biology'} = 'Boring';
# determining size of hash after
# adding an element
@keys = keys %subjects;
$size = @keys;
print "Hash size is $size\n";
# removing an element from hash
delete $subjects{'Chemistry'};
# determining size of hash after
# removing an element
@keys = keys %subjects;
$size = @keys;
print "Hash size is $size\n";
# modifying an element of hash
$subjects{'Mathematics'} = 'Intriguing';
# looping over the hash
for(keys %subjects){
print("$_ is $subjects{$_}\n");
}
Output:Hash size is 4
Hash size is 5
Hash size is 4
Mathematics is Intriguing
Physics is Laws
Programming is Fun
Biology is Boring
Similar Reads
Perl | Getting the Number of Elements of an Array An array in Perl is a variable used to store an ordered list of scalar values. An array variable is preceded by an "at" (@) sign. The size of an array can be determined using the scalar context on the array which returns the number of elements in the array Example 1: Perl #!/usr/bin/perl # Initializ
2 min read
Perl | Multidimensional Arrays Multidimensional arrays in Perl are the arrays with more than one dimension. Technically there is no such thing as a multidimensional array in Perl but arrays are used to act as they have more than one dimension. Multi dimensional arrays are represented in the form of rows and columns, also knows as
6 min read
Perl | Useful Hash functions A hash is a set of key-value pairs. Perl stores elements of a hash such that it searches for the values based on its keys. Perl provides various functions to perform operations on Hashes, such as to return values of the hash, to delete elements from a hash, etc. Example: Perl #!/usr/bin/perl # Initi
2 min read
Perl | Arrays In Perl, array is a special type of variable. The array is used to store the list of values and each object of the list is termed as an element. Elements can either be a number, string, or any type of scalar data including another variable. Example: @number = (50, 70, 46); @names = ("Geeks", "For",
6 min read
PHP | hash_algos() Function The hash_algos() function is an inbuilt function in PHP which is used to return a list of registered hashing algorithms. Syntax: array hash_algos( void ) Parameter: This function does not accepts any parameter. Return Value: This function returns a numerically indexed array which contains the list o
2 min read
Perl | Hash Operations Prerequisite: Perl Hashes, Perl Hash As most readers likely know, the hash stores data by using a mechanism called Hashing. In hashing, a key is used to determine a value or data. These keys must be unique and are then used as the index at which the data associated with the key is stored. This data
8 min read
How to Return an Array that Contains an Array and Hash in Ruby Method? In this article, we will learn how to return an array that contains an array and hash. We can return an array that contains an array and hash using the methods mentioned below: Table of Content Using an Explicit Return StatementUsing Implicit Return StatementUsing Array Literal and Hash ConstructorU
3 min read
How to convert Array to Hash in Ruby? In this article, we will discuss how to convert an array to a hash in Ruby. Converting an array to a hash can be useful when we have data in an array format and need to organize it into key-value pairs for easier access and manipulation. Table of Content Converting array to hash using Hash::[] const
3 min read
Perl | keys() Function keys() function in Perl returns all the keys of the HASH as a list. Order of elements in the List need not to be same always, but, it matches to the order returned by values and each function. Syntax: keys(HASH) Parameter: HASH: Hash whose keys are to be printed Return: For scalar context, it return
1 min read
Perl | each() Function This function returns a Two-element list consisting of the key and value pair for the next element of a hash when called in List context, so that you can iterate over it. Whereas it returns only the key for the next element of the hash when called in scalar context. Syntax: each MY_HASH Parameter: M
1 min read