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 does not have to be unique. It may be duplicated.
Hash is a data structure that stores data by maintaining relations between keys and values or key/value pairs. Given a key, we can find its value. Key/value pairs are mutable objects and hence, they can be changed whenever you want to. The key in a hash can be further defined as an object that is used to retrieve a value. The main advantage of using a hash over arrays is that hash allows the execution time of basic operations like, to get a value or to set a value at a particular key (index in case of arrays), to remain constant even for large data sets.
Note that hashes in Perl are not ordered. This means that when you iterate over a hash, you may not extract the values in the same order in which they were inserted.
The values stored in a hash can of type integer, float, string, boolean, arrays and hash itself.
Example
my %hash = (
'MyVehicle' => 'Car' ,
'Model' => 1234,
'Speed' => 60.7,
'Traffic' => { 'Red' => 'Stop' ,
'Yellow' => 'Look and move' ,
'Green' => 'Go' },
'AllVehicles' => [ 'Car' , 'Cycle' ,
'Bus' , 'Auto' ]);
print "Traffic : $hash{'Traffic'}\n" ;
print "AllVehicles : $hash{'AllVehicles'}\n" ;
|
Output:
Traffic : HASH(0x242af30)
AllVehicles : ARRAY(0x24471f8)
Here, the data type at key Traffic is hash and at key AllVehicles is of type array. So, the output is the address of the first element of the hash and array respectively.
Further, many operations or manipulations can be performed on a hash which are explained below:
Operations on Hash
Perl hash operations include various operations which are acted upon hash to store and retrieve data more efficiently. The most commonly used operations in the hash are :
- Accessing the keys and values in a hash.
- Modifying the values of particular keys.
- Loop over to the hash.
Each operation in Perl Hash is explained below with examples:
Look up/Accessing Perl hash values or keys
Looking up or accessing means to able to access each and every key/value pair of a hash for further manipulation. Keys in Perl store elements of a Hash in such an optimal way that its values can be fetched very fast. Values in a hash can be looked up using respective key name embedded in between {} brackets.
Syntax : $hash_name{key_name};
Example
my %hash = ( 'MyVehicle' => 'Car' ,
'Model' => 1234,
'Speed' => 60.7,
'Traffic' => { 'Red' => 'Stop' ,
'Yellow' => 'Look and move' ,
'Green' => 'Go' },
'AllVehicles' => [ 'Car' , 'Cycle' ,
'Bus' , 'Auto' ]);
@k = keys %hash ;
print "Keys are : " ;
print join ( ", " , @k ), "\n" ;
@v = values %hash ;
print "Values are : " ;
print join ( ", " , @v ), "\n" ;
print "Speed is : $hash{'Speed'}\n" ;
print "Yellow light indicates : $hash{'Traffic'}{'Yellow'}\n" ;
print "$hash{'AllVehicles'}[3] is a type of vehicle \n" ;
|
Output:
Keys are : AllVehicles, MyVehicle, Speed, Traffic, Model
Values are : ARRAY(0x9361f8), Car, 60.7, HASH(0x919f30), 1234
Speed is : 60.7
Yellow light indicates : Look and move
Auto is a type of vehicle
Modify hash elements
Values in a hash are not fixed, that is they are prone to change and Perl provide this ability to modify and update the values in a hash. For a given key, to modify or update its corresponding value use following syntax :
Syntax : $hash{‘Key’} = modified_value;
To Modify a given key without changing its corresponding value, simply create an additional key which is the modified key and assign value (for which you want this new key) to this key and then delete the previous key/value pair using delete keyword.
Example :
my %hash = ( 'MyVehicle' => 'Car' ,
'Model' => 1234,
'Speed' => 60.7,
'Traffic' => { 'Red' => 'Stop' ,
'Yellow' => 'Look and move' ,
'Green' => 'Go' },
'AllVehicles' => [ 'Car' , 'Cycle' ,
'Bus' , 'Auto' ]);
print ( "Previous Model number is " ,
$hash { 'Model' }, "\n" );
$hash { 'Model' } = 7717;
print ( "New Model number is " ,
$hash { 'Model' }, "\n" );
@k = keys %hash ;
print "Previous Keys are : \n" ;
print join ( ", " , @k ), "\n" ;
$hash { 'Mine' } = 'Car' ;
delete $hash { 'MyVehicle' };
@k_n = keys %hash ;
print "New Keys are : \n" ;
print join ( ", " , @k_n ), "\n" ;
|
Output:
Previous Model number is 1234
New Model number is 7717
Previous Keys are :
MyVehicle, AllVehicles, Model, Traffic, Speed
New Keys are :
Mine, Speed, Traffic, Model, AllVehicles
Loop over Perl hash values
Perl allows to Loop over its Hash values. It means the hash is iterative type and one can iterate over its keys and values using ‘for’ loop and ‘while’ loop. In Perl, hash data structure is provided by the keys() function similar to the one present in Python programming language. This keys() function allows you to get a list of keys of the hash in scalars which can be further used to iterate over the values of respective keys of the hash.
Syntax keys %Hash
Besides, Perl provides two ways to loop over all the elements in a hash.
- Perl foreach loop
- Perl while loop with each function
my %hash = ( 'MyVehicle' => 'Car' ,
'Model' => 1234,
'Speed' => 60.7,
'Traffic' => { 'Red' => 'Stop' ,
'Yellow' => 'Look and move' ,
'Green' => 'Go' },
'AllVehicles' => [ 'Car' , 'Cycle' ,
'Bus' , 'Auto' ]);
foreach my $key ( keys %hash )
{
$value = $hash { $key };
print "Value of $key is $value\n" ;
}
while (( $key , $value ) = each ( %hash ))
{
$value = $hash { $key };
print "Value of $key is $value\n" ;
}
|
Output:
Value of Model is 1234
Value of MyVehicle is Car
Value of Traffic is HASH(0x1049f30)
Value of AllVehicles is ARRAY(0x10661f8)
Value of Speed is 60.7
Value of Model is 1234
Value of MyVehicle is Car
Value of Traffic is HASH(0x1049f30)
Value of AllVehicles is ARRAY(0x10661f8)
Value of Speed is 60.7
In the above example, the code gives address of the first element of the array and the hash stored at key ‘AllVehicles’ and ‘Traffic’ respectively. To overcome this, we have to loop over inside the array and hash also.
Example
my %hash = ( 'MyVehicle' => 'Car' ,
'Model' => 1234,
'Speed' => 60.7,
'Traffic' => { 'Red' => 'Stop' ,
'Yellow' => 'Look and move' ,
'Green' => 'Go' },
'AllVehicles' => [ 'Car' , 'Cycle' ,
'Bus' , 'Auto' ]);
my @array = @{ $hash { 'AllVehicles' }};
print "AllVehicles include \n" ;
foreach my $ele ( @array )
{
print "$ele\n" ;
}
print "\nTraffic includes\n" ;
foreach my $val ( keys %{ $hash { 'Traffic' }})
{
print "Key : $val, value : $hash{'Traffic'}{$val}\n" ;
}
|
Output:
AllVehicles include
Car
Cycle
Bus
Auto
Traffic includes
Key : Yellow, value : Look and move
Key : Green, value : Go
Key : Red, value : Stop
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
06 May, 2019
Like Article
Save Article