Open In App

Perl | Hash Operations

Improve
Improve
Like Article
Like
Save
Share
Report
    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




#!/usr/bin/perl
  
# Creating a simple hash containing
# different types of values
my %hash = ( # value type string
            'MyVehicle' => 'Car',
              
            # value type integer
            'Model' => 1234,
              
            # value type float
            'Speed' => 60.7,    
              
            # value type hash
            'Traffic' => {'Red' => 'Stop',         
                        'Yellow' => 'Look and move'
                        'Green' => 'Go'},
            # value type array
            'AllVehicles' => ['Car', 'Cycle'
                              'Bus', 'Auto']);
  
# printing values stored 
# at key 'Traffic' and 'AllVehicles'
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 :

    1. Accessing the keys and values in a hash.
    2. Modifying the values of particular keys.
    3. 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




    # Perl program to demonstrate 
    # accessing of the hash values
    my %hash = ('MyVehicle' => 'Car'
                'Model' => 1234, 
                'Speed' => 60.7, 
                  
                # value type hash
                'Traffic' => {'Red' => 'Stop',             
                              'Yellow' => 'Look and move'
                              'Green' => 'Go'},
                                
                # value type array
                'AllVehicles' => ['Car', 'Cycle'
                                  'Bus', 'Auto']);
      
    # Creating array containing 
    # keys of the hash
    @k = keys %hash;         
      
    # print all keys of the hash
    print "Keys are : ";
    print join(", ", @k), "\n";
      
    # Creating array containing
    # values of the hash
    @v = values %hash;             
      
    # print value of all values
    print "Values are : ";
    print join(", ", @v), "\n";
      
    # accessing individual values of the keys
    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 :




      # Perl program to demonstrate the 
      # Modification of an element of a Hash 
        
      # creating a hash
      my %hash = ('MyVehicle' => 'Car'
                  'Model' => 1234, 
                  'Speed' => 60.7, 
                    
                  # value type hash
                  'Traffic' => {'Red' => 'Stop',             
                                'Yellow' => 'Look and move'
                                'Green' => 'Go'},
                    
                  # value type array
                  'AllVehicles' => ['Car', 'Cycle'
                                    'Bus', 'Auto']);
        
      # previous value of key 'Model'
      print ("Previous Model number is "
                   $hash{'Model'}, "\n");
        
      # modifying value of key 'Model'
      $hash{'Model'} = 7717;
        
      # new value of key 'Model'
      print ("New Model number is "
              $hash{'Model'}, "\n");
        
      # Changing key from 'MyVehicle' to 'Mine' 
      # without changing its corresponding value
      @k = keys %hash;
        
      # printing previous keys
      print "Previous Keys are : \n";     
      print join(", ", @k), "\n"
        
      $hash{'Mine'} = 'Car';
        
      # deleting 'MyVehicle' key/value pair
      delete $hash{'MyVehicle'};         
        
      @k_n = keys %hash;
      print "New Keys are : \n";    
        
      # printing new keys
      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.

    1. Perl foreach loop
    2. Perl while loop with each function




    # Perl program to demonstrate the 
    # looping over a hash using its keys
      
    # creating a hash
    my %hash = ('MyVehicle' => 'Car'
                'Model' => 1234, 
                'Speed' => 60.7, 
                  
                # value type hash
                'Traffic' => {'Red' => 'Stop',             
                              'Yellow' => 'Look and move'
                              'Green' => 'Go'},
                  
                # value type array
                'AllVehicles' => ['Car', 'Cycle',
                                  'Bus', 'Auto']);
      
    # Case 1: When hash is not large 
      
    # for loop to loop over the hash
    foreach my $key (keys %hash)
    {
          
        # do stuff
        $value = $hash{$key};
        print "Value of $key is $value\n"
    }
      
    # Case 2: When hash is very large 
      
    # traversing the hash using "each" function
    while(($key, $value) = each (%hash))
    {
          
        # do stuff
        $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




    # Perl program to demonstrate the 
    # looping over a multidimensional hash
      
    # creating a hash
    my %hash = ('MyVehicle' => 'Car'
                'Model' => 1234, 
                'Speed' => 60.7, 
                  
                # value type hash
                'Traffic' => {'Red' => 'Stop',             
                              'Yellow' => 'Look and move'
                              'Green' => 'Go'},
                                
                # value type array
                'AllVehicles' => ['Car', 'Cycle',
                                  'Bus', 'Auto']);
      
    # Loop over the key storing array 
    my @array = @{$hash{'AllVehicles'}};
    print "AllVehicles include \n";
      
    # for loop to loop over the array
    foreach my $ele (@array)
    {
        print "$ele\n";
    }
      
    # Loop over the key storing hash
    print "\nTraffic includes\n";
      
    # for loop to loop over the hash
    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
    


    Last Updated : 06 May, 2019
    Like Article
    Save Article
    Previous
    Next
    Share your thoughts in the comments
Similar Reads