The Wayback Machine - https://web.archive.org/web/20241001130352/https://www.geeksforgeeks.org/perl-hash-operations/
Open In App

Perl | Hash Operations

Last Updated : 06 May, 2019
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
    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
    


    Previous Article
    Next Article

Similar Reads

Perl | Basic Syntax of a Perl Program
Perl is a general purpose, high level interpreted and dynamic programming language. Perl was originally developed for the text processing like extracting the required information from a specified text file and for converting the text file into a different form. Perl supports both the procedural and Object-Oriented programming. Perl is a lot similar
10 min read
Sorting Hash in Perl
Prerequisite: Perl | Hashes Set of key/value pair is called a Hash. Each key in a hash structure are unique and of type strings. The values associated with these keys are scalar. These values can either be a number, string or a reference. A Hash is declared using my keyword. Let us consider an example to understand the concept of sorting the hash.
6 min read
Perl Hash
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. Hash variables start with a '%' sign. Perl requires the keys of a hash to be strings, whereas the values can be any scalars. These values can either be a number, string or reference. If non-string values are used as the keys, i
4 min read
Perl | Hash in Scalar and List Context
Prerequisite: Perl Hash Hash in Perl is a set of key/value pairs. Perl provides us the flexibility to assign the hash to a List type and a Scalar type, known as LIST Context and SCALAR Context respectively. Hash in LIST Context The assignment of a hash to a list type in Perl is accomplished by making a list with the keys and values as its elements.
5 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: #!/usr/bin/perl # Initializing hash %hash1 = ('Welcome' => 10, 'to' => 2
2 min read
Perl | Use of Hash bang or Shebang line
Practical Extraction and Reporting Language or Perl is an interpreter based language. Hash-bangs or shebangs are useful when we are executing Perl scripts on Unix-like systems such as Linux and Mac OSX. A Hashbang line is the first line of a Perl program and is a path to the Perl binary. It allows invoking the Perl scripts directly, without passing
3 min read
Perl - Creating a Hash from an Array
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 arra
4 min read
Perl | Directories with CRUD operations
Perl is universal and cross-platform programming language mainly used for text manipulation and used in developing many software application like web development, graphical user interface application etc. It is preferred over other programming languages as it is faster, powerful and Perl has a lot of shortcuts which helps in writing a quick script
5 min read
Perl | chomp() Function
The chomp() function in Perl is used to remove the last trailing newline from the input string. Syntax: chomp(String) Parameters: String : Input String whose trailing newline is to be removed Returns: the total number of trailing newlines removed from all its arguments Example 1: C/C++ Code #!/usr/bin/perl # Initialising a string $string = &quo
2 min read
Perl | Backtracking in Regular Expression
In Perl, a Regular expression(a.k.a regexes or regexps or REs) is a way of describing a set of strings without having to list all strings in your program or simply we can say that it is a sequence of characters that are used for pattern matching. In Perl, regular expressions have different uses: Firstly, they are used in conditionals to determine w
3 min read
Perl | Searching in a File using regex
Prerequisite: Perl | Regular Expressions Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to host language and are not the same as in PHP, Python, etc. Sometimes these are termed as "Perl 5 Compatible Regular Expressions". To use the Regex, Bindi
6 min read
Perl | Operators | Set - 1
Operators are the main building block of any programming language. Operators allow the programmer to perform different kinds of operations on operands. In Perl, operators symbols will be different for different kind of operands(like scalars and string). Operators Can be categorized based upon their different functionality: Arithmetic OperatorsRelat
12 min read
Perl | lt operator
'lt' operator in Perl is one of the string comparison operators used to check for the equality of the two strings. It is used to check if the string to its left is stringwise less than the string to its right. Syntax: String1 lt String2 Returns: 1 if left argument is less than the right argument Example 1: #!/usr/local/bin/perl # Initializing Strin
1 min read
Perl | chop() Function
The chop() function in Perl is used to remove the last character from the input string. Syntax: chop(String) Parameters: String : It is the input string whose last characters are removed. Returns: the last removed character. Example 1: #!/usr/bin/perl # Initialising a string $string = "GfG is a computer science portal"; # Calling the chop
1 min read
Perl | rename() Function
rename() function in Perl renames the old name of a file to a new name as given by the user. Syntax: rename(old_file_path, new_file_path) Parameters: old_file_path: path of the old file along with its name new_file_path: path of the new file along with its name Returns 0 on failure and 1 on success Example: #!/usr/bin/perl -w # Calling the rename()
1 min read
Perl | Subroutines or Functions
A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language user want to reuse the code. So the user puts the section of code in function or subroutine so that there will be no need to write code again and again. In Perl, the terms function, subroutine, and method are the same but in s
2 min read
Perl | Decision Making (if, if-else, Nested–if, if-elsif ladder, unless, unless-else, unless-elsif)
Decision Making in programming is similar to decision making in real life. In programming, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance
6 min read
Perl | Loops (for, foreach, while, do...while, until, Nested loops)
Looping in programming languages is a feature which facilitates the execution of a set of instructions or functions repeatedly while some condition evaluates to true. Loops make the programmers task simpler. Perl provides the different types of loop to handle the condition based situation in the program. The loops in Perl are : for Loop "for" loop
7 min read
Perl | Comparing Scalars
Prerequisite: Scalars in Perl Perl has two types of comparison operator sets. Just like other mathematical operators, instead of performing operations, these operators compare scalars. There are two types of sets of Perl comparison operators. One is for numeric scalar values and one is for string scalar values. Both the types are illustrated in bel
6 min read
Perl | String functions (length, lc, uc, index, rindex)
String in Perl is a sequence of character enclosed within some kinds of quotation marks. Perl string can contain UNICODE, ASCII and escape sequence characters. Perl provides the various function to manipulate the string like any other programming language. Some string functions of Perl are as follows: length() lc() uc() index() rindex() length(): T
4 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", "Geeks"); Array Creation: In Perl programming ever
6 min read
Perl | Data Types
Data types specify the type of data that a valid Perl variable can hold. Perl is a loosely typed language. There is no need to specify a type for the data while using in the Perl program. The Perl interpreter will choose the type based on the context of the data itself. There are 3 data types in Perl as follows: ScalarsArraysHashes(Associative Arra
3 min read
Perl | String Operators
Operators are the foundation of any programming language. Thus, the functionality of Perl programming language is incomplete without the use of operators. A user can define operators as symbols that help to perform specific mathematical and logical computations on operands. String are scalar variables and start with ($) sign in Perl. The String is
4 min read
Perl | Hashes
Set of key/value pair is called a Hash. Each key in a hash structure are unique and of type strings. The values associated with these keys are scalar. These values can either be a number, string or a reference. A Hash is declared using my keyword. The variable name is preceded by the dollar sign($)followed by key under curly braces and the value as
5 min read
Perl | Regular Expressions
Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to the host language and is not the same as in PHP, Python, etc. Sometimes it is termed as “Perl 5 Compatible Regular Expressions“. To use the Regex, Binding operators like ‘=~‘(Regex Operator) and
2 min read
Perl | Regex Cheat Sheet
Regex or Regular Expressions are an important part of Perl Programming. It is used for searching the specified text pattern. In this, set of characters together form the search pattern. It is also known as regexp. When user learns regular expression then there might be a need for quick look of those concepts which he didn't use often. So to provide
6 min read
Introduction to Perl
Perl is a general-purpose, high level interpreted and dynamic programming language. It was developed by Larry Wall, in 1987. There is no official Full form of the Perl, but still, the most used expansion is "Practical Extraction and Reporting Language". Some of the programmers also refer Perl as the "Pathologically Eclectic Rubbish Lister" Or "Prac
9 min read
Perl | Regex Character Classes
Character classes are used to match the string of characters. These classes let the user match any range of characters, which user don’t know in advance. Set of characters that to be matched is always written between the square bracket []. A character class will always match exactly for one character. If match not found then the whole regex matchin
3 min read
Perl | Special Character Classes in Regular Expressions
There are many different character classes implemented in Perl and some of them used so frequently that a special sequence is created for them. The aim of creating a special sequence is to make the code more readable and shorter. The Special Character Classes in Perl are as follows: Digit \d[0-9]: The \d is used to match any digit character and its
4 min read
Perl | Subroutines or Functions | Set - 2
Prerequisite: Subroutines or Functions in Perl A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language user want to reuse the code. So the user puts the section of code in function or subroutine so that there will be no need to write code again and again. In this article we will di
4 min read
Article Tags :