FreeKB - Perl (Scripting) loop hash array (key value pairs)
Perl (Scripting) - loop hash array (key value pairs)

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 a hash named %hash contain contains a single key (foo), and the key is an array, as indicated by the [ ] characters.

my %hash = ( 'foo' => [ { 'name' => 'John Doe', 'role' => 'Engineer' } ] );

 

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' => [
                     {
                       'name' => 'John Doe',
                       'role' => 'Engineer'
                     }
                   ]
        };

 

You can loop through the foo key to print the value associated with the key.

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

 

Which should return the following.

John Doe
Engineer

 



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 c0c02 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   |