Bootstrap FreeKB - Perl (Scripting) - Loop through values in an array in a hash
Perl (Scripting) - Loop through values in an array 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 a hash named %hash which contains a single key (foo), and the key is an array, as indicated by the [ ] characters.

my %hash = ( 'foo' => [ 'John Doe','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 = {
          'foo' => [ 
                     'John Doe', 
                     'Jane Doe'
                   ]
        };

 

Here is how you would loop through the values in the foo key.

foreach my $foo (@{$hash{foo}}) {
  print "$foo \n";
}

 

Which should return the following.

John Doe
Jane Doe

 


Let's say you a hash named %hash where the bar key is a child of the foo key, which means the hash is multidimensional. In this example, the bar key is an array, as indicated by the [ ] characters.

my %hash = ( 'foo' => { 'bar' => [ 'John Doe','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 = {
          'foo' => {
                     'bar' => [
                                'John Doe',
                                'Jane Doe'
                              ]
                   }
        };

 

Here is how you would loop through the values in the bar key.

foreach my $value (@{$hash{foo}->{bar}}) {
  print "$value \n";
}

 

Which should return the following.

John Doe
Jane Doe

 


Multiple Arrays

Let's consider the scenario where there are multiple arrays in the hash. Let's say you have the following, where the foo key is an array, and the bar key which is also an array is within the foo key.

my %hash = ( 'foo' => [ { 'bar' => [ 'John Doe','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 = {
          'foo' => [
                     {
                       'bar' => [
                                  'John Doe',
                                  'Jane Doe'
                                ]
                     }
                   ]
        };

 

And here is how you would loop over the values in the bar key.

foreach my $foo (@{$hash{foo}}) {
  foreach my $value (@{$foo->{bar}}) {
    print "$value\n";
  }
}

 

Which should return the following.

Hello
World

 




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