Bootstrap FreeKB - Perl (Scripting) - Sort keys in a hash
Perl (Scripting) - Sort keys in a hash

Updated:   |  Perl (Scripting) articles

In Perl, there are 2 different kinds of hashes.

  • A hash, which is defined by the % and ( ) characters - %hash = ( );
  • A reference hash, which is defined with the $ and { } characters - $hash = { };

 

Let's say you have the following hash. In this example, the hash has two keys, foo and bar.

my %hash;
$hash{foo} = "Hello";
$hash{bar} = "World";

 

The following can be done to sort the keys alphabetically within the foreach loop.

This will not actually sort or modify the hash. This only sorts the keys as part of the foreach loop

foreach my $key (sort keys %hash) {
  print "$key \n";
}

 

Which should return the following.

bar
foo

 

Dumper can be used to display the structure of the hash.

use Data::Dumper;
print Dumper \%hash;

 

Which should return the following. In this example, the key's are not sorted alphabetically.

$VAR1 = {
           'foo' => 'Hello',
           'bar' => 'World'
        };

 

The following can be done to sort the keys alphabetically.

This will not actually sort or modify the hash. This only sorts the keys for the Dumper output.

$Data::Dumper::Sortkeys = sub { [ sort keys %hash ] };

 

Printing the hash . . .

print Dumper \%hash;

 

. . . should return the following. Now, the keys are sorted alphabetically.

$VAR1 = {
           'bar' => 'World',
           'foo' => 'Hello'
        };

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 880e23 in the box below so that we can be sure you are a human.