FreeKB - Perl (Scripting) loop hash array (keys)
Perl (Scripting) - loop hash array (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 a hash named %hash which contains two keys, foo and bar. Both keys are arrays, as indicated by the [ ] characters.

my %hash = ( 'foo' => [ 'John Doe', 'Jane Doe' ], 'bar' => [ 'Engineer', 'Sales' ] );

 

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

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

 

Which should return something like this.

$VAR1 = {
          'bar' => [
                     'Engineer',
                     'Sales'
                   ],
          'foo' => [
                     'John Doe',
                     'Jane Doe'
                   ]
        };

 

Here is how you would loop through the top level keys.

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

 

Which should return the following.

foo
bar

 



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