Bootstrap FreeKB - Perl (Scripting) - Loop through keys in a hash
Perl (Scripting) - Loop through 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 = { };

 

In this example, there are two keys, foo and bar. The foo key is a hash (single key value pair) and the bar key is an array (single key that can contain multiple values).

my %hash = ( 'foo' => '', 'bar' => [] );

 

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

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

 

Which should produce the following.

$VAR1 = {
          'foo' => '',
          'bar' => []
        };

 

Looping through the hash . . .

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

 

. . . will print the keys.

foo
bar

 

Let's say you a hash named %hash where the foo and bar keys are children of the primary key, which means the hash is multidimensional.

my %hash = ( 'primary' => { 'foo' => 'John Doe', 'bar' => 'Jane Doe' } );

 

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

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

 

Which should return something like this.

$VAR1 = {
          'primary' => {
                         'bar' => 'Jane Doe',
                         'foo' => 'John Doe'
                       }
        };

 

Here is how you would loop through the keys below the primary key.

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

 

Which should return the following.

foo
bar

 




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 76a0b8 in the box below so that we can be sure you are a human.