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.

Example: Consider a hash with the names of the students in a class and with their average score. Here, the name of the students are the keys and their average scores are the values. Print this hash using foreach loop on the student names returned by the keys function.



filter_none

edit
close

play_arrow

link
brightness_4
code

# Perl program to demonstrate 
# the concept of hash
use strict;
use warnings;
use 5.010;
  
# Creating a hash of studentnames 
# and their average score
my %studentnames = (
Martha => 14,
Vivek => 27,
Earl => 31,
Marty => 16.5,
Jason => 25.2,
Socrates => 29.5,
Uri => 19.6,
Nitin => 30,
Plato => 39,
);
  
# displaying the keys and values of Hash
# using the foreach loop and keys function 
# output may be different each 
# time when you run the code
foreach my $name (keys %studentnames) {
      
    # printing the keys and values of hash
    printf "%-8s %s\n", $name, $studentnames{$name};
}

chevron_right


Output:

Marty    16.5
Jason    25.2
Plato    39
Vivek    27
Socrates 29.5
Martha   14
Earl     31
Uri      19.6
Nitin    30

Note: The output may contain any random order depends on the system and the version of Perl.

Hashes can be sorted in many ways as follows:

  • Sorting the Hash according to the ASCII values of its keys: Generally, sorting is based on ASCII table. It means sorting will keep all the upper-case letters in front of all the lower-case letters. This is the default behavior of the sorting. The above example code is sorted according to the ASCII values of its keys.
  • Sorting the Hash according to the alphabetical order of its keys: Here, the keys are sorted alphabetically.

    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Perl program to demonstrate 
    # sorting of the hash according 
    # alphabetical order of its keys
    use strict;
    use warnings;
    use 5.010;
      
    # Creating a hash of studentnames 
    # and their average score
    my %studentnames = (
    Martha => 14,
    Vivek => 27,
    Earl => 31,
    Marty => 16.5,
    Jason => 25.2,
    Socrates => 29.5,
    Uri => 19.6,
    Nitin => 30,
    Plato => 39,
    );
      
    # sorting the hash according 
    # alphabetical order of its keys
    foreach my $name (sort {lc $a cmp lc $b} keys %studentnames
    {
        printf "%-8s %s\n", $name, $studentnames{$name};
    }

    chevron_right

    
    

    Output:

    Earl     31
    Jason    25.2
    Martha   14
    Marty    16.5
    Nitin    30
    Plato    39
    Socrates 29.5
    Uri      19.6
    Vivek    27
    
  • Sorting according to the values of Hash: You can also sort the hash according to the values of hash as follows:

    Example 1: Sorting the hash values according to the ASCII table.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Perl program to demonstrate 
    # sorting of the hash according
    # to the values of Hash
    use strict;
    use warnings;
    use 5.010;
      
    # Creating a hash of studentnames 
    # and their average score
    my %studentnames = (
    Martha => 14,
    Vivek => 27,
    Earl => 31,
    Marty => 16.5,
    Jason => 25.2,
    Socrates => 29.5,
    Uri => 19.6,
    Nitin => 30,
    Plato => 39,
    );
      
    # sorting of the hash according
    # to ASCII code of values of Hash
    foreach my $name (sort values %studentnames
    {
        say $name;
    }

    chevron_right

    
    

    Output:

    14
    16.5
    19.6
    25.2
    27
    29.5
    30
    31
    39
    

    Example 2: Sorting according to the numerical value of Values of hash as follows:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Perl program to demonstrate 
    # sorting of the hash according
    # to the values of Hash
    use strict;
    use warnings;
    use 5.010;
      
    # Creating a hash of studentnames 
    # and their average score
    my %studentnames = (
    Martha => 14,
    Vivek => 27,
    Earl => 31,
    Marty => 16.5,
    Jason => 25.2,
    Socrates => 29.5,
    Uri => 19.6,
    Nitin => 30,
    Plato => 39,
    );
      
    # sorting of the hash according
    # to the numerical value of
    # Values of hash
    foreach my $name (sort {$a<=>$b} values %studentnames
    {
        say $name;
    }

    chevron_right

    
    

    Output:

    14
    16.5
    19.6
    25.2
    27
    29.5
    30
    31
    39
    
  • Sort the keys of the hash according to the values: You can also sort the keys of hash according to the given values.

    Example 1: In the below program, <=> is termed as the spaceship operator. If you will run the code again and again then you can notice the difference in the output. Sometimes you find Plato before the Nitin and vice-versa.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Perl program to demonstrate the
    # Sorting of keys of the hash 
    # according to the values
    use strict;
    use warnings;
    use 5.010;
      
    # Creating a hash of studentnames 
    # and their average score
    my %studentnames = (
    Martha => 14,
    Vivek => 27,
    Earl => 31,
    Marty => 16.5,
    Jason => 25.2,
    Socrates => 29.5,
    Uri => 19.6,
    Nitin => 45,
    Plato => 45,
    );
      
    # Sort the keys of the hash
    # according to the values
    # Here $a and $b are the 
    # placeholder variable of sort
    foreach my $name (sort {$studentnames{$a} <=> 
           $studentnames{$b}} keys %studentnames
    {
        printf "%-8s %s\n", $name, $studentnames{$name};
    }

    chevron_right

    
    

    Output:

    Martha   14
    Marty    16.5
    Uri      19.6
    Jason    25.2
    Vivek    27
    Socrates 29.5
    Earl     31
    Plato    45
    Nitin    45
    

    Example 2: To solve the above code, keys having the same values can be sorted according to the ASCII table as follows:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Perl program to demonstrate the
    # Sorting of keys of the hash 
    # according to the values
    use strict;
    use warnings;
    use 5.010;
      
    # Creating a hash of studentnames 
    # and their average score
    my %studentnames = (
    Martha => 14,
    Vivek => 27,
    Earl => 31,
    Marty => 16.5,
    Jason => 25.2,
    Socrates => 29.5,
    Uri => 19.6,
    Nitin => 45,
    Plato => 45,
    );
      
    # keys that have the same value 
    # will be sorted according the 
    # ASCII table
    foreach my $name (sort { $studentnames{$a} <=> $studentnames{$b} or
                                    $a cmp $b } keys %studentnames) {
        printf "%-8s %s\n", $name, $studentnames{$name};
    }

    chevron_right

    
    

    Output:

    Martha   14
    Marty    16.5
    Uri      19.6
    Jason    25.2
    Vivek    27
    Socrates 29.5
    Earl     31
    Nitin    45
    Plato    45
    

    Explanation: Here you can see the key Nitin and Plato are sorted according to the ASCII table. It doesn’t matter how many times you run the code, the output will remain the same.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.