Bootstrap FreeKB - Perl (Scripting) - Count keys in a hash that contains an array
Perl (Scripting) - Count keys in a hash that contains an array

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 define a hash array named %hash that contains a single key (foo). The foo key will contain an array of values. The [ ] characters are used to set the foo key as an array.

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

 

The following can be used to print the number of keys in the hash.

my $keys   = keys %hash;
print "keys   = $keys \n";

 

Which should return the following.

keys = 1

 

Or if the hash contains two keys.

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

 

The following should be returned.

keys = 2

 

Let's say the hash is multidimensional, where the foo key is the parent and the bar key is the child.

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

 

The following should still be returned.

keys = 1

 

Here is how you would count the child keys below a parent key.

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

 




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