FreeKB - Perl (Scripting) Hash (sort keys)
Perl (Scripting) - Hash (sort keys)

In Perl, there are 3 different kinds of hashes.

  • A regular hash, which is defined by the % and ( ) characters - %hash = ( );
  • A reference hash, which is defined with the $ and { } characters = $hash = { };
  • A hash array, 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'
        };

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




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




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |