Perl (Scripting) - Count values in a hash that contains an array

by
Jeremy Canfield |
Updated: August 10 2022
| 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 values in the foo key.
my $count = values $hash{foo};
print "values = $count \n";
Which should return the following.
values = 0
Let's say the foo key contains 2 values.
my %hash = ( 'foo' => [ 'John Doe', 'Jane Doe' ] );
Now, the following should be returned.
values = 2
Did you find this article helpful?
If so, consider buying me a coffee over at