Perl (Scripting) - Count keys and values in a hash

by
Jeremy Canfield |
Updated: September 23 2024
| 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 have the following empty hash that contains no keys and no values.
my %hash;
The following can be used to print the number of keys and values in the hash.
my $keys = keys %hash;
my $values = values %hash;
print "keys = $keys \n";
print "values = $values \n";
Which should return the following.
keys = 0
values = 0
Hash with keys and values
Let's append some keys and values. In this example, the hash has three keys (employee, id, department) and three values (John Doe, 123456, Engineering)
my %hash;
$hash{employee} = "John Doe";
$hash{id} = "123456";
$hash{department} = "Engineering";
Print the number of keys and values in the hash.
my $keys = keys %hash;
my $values = values %hash;
print "keys = $keys \n";
print "values = $values \n";
Which should return the following.
keys = 3
values = 3
Did you find this article helpful?
If so, consider buying me a coffee over at