How to count the number of keys in a Perl hash?


There are times when we would want to know how many key-value pairs are present in a hash. These key-value pair counts are also known as the size of the hash. In Perl, we can find the number of keys in a Perl hash by using the "scalar" keyword or "keys" keyword.

In this tutorial, we will explore two Perl examples where we will calculate the number of keys in a hash.

Example

Consider the code shown below. In this code, we have declared a hash named "countries" and in that hash, we have different countries, each having a different value. We are using the "keys" keyword to count the number of keys in the hash.

# create the Perl hash
$countries{'India'} = 12.00;
$countries{'China'} = 1.25;
$countries{'Russia'} = 3.00;
$countries{'USA'} = 9.1;

# get the hash size
$size = keys %countries;

# print the hash size
print "The hash contains $size key-value pairs.\n";

Output

If you run the above code in a Perl compiler, then we will get the following output in the terminal.

The hash contains 4 key-value pairs.

Example

Now let's see how you can use the "scalar" keyword to find out the number of keys in the hash. Consider the code shown below.

In this code, we have declared a hash named "countries" and in that hash, we have different countries, each having a different value. Then we are using the "scalar" keyword to find out the number of keys present in the hash.

# create the Perl hash
$countries{'India'} = 12.00;
$countries{'China'} = 1.25;
$countries{'Russia'} = 3.00;
$countries{'USA'} = 9.1;

# get the hash size
$size = scalar % countries;

# print the hash size
print "The hash contains $size key-value pairs.\n";

Output

If you run the above code in a Perl compiler, then we will get the following output in the terminal.

The hash contains 4 key-value pairs.

Updated on: 04-Apr-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements