Perl hash size - How to get the size of a hash in Perl

Perl hash size FAQ: How do I get the size of a hash in Perl?

Short answer: To get the size of a Perl hash (the Perl hash size), use the Perl "keys" function, and assign it to a scalar value, like this:

$size = keys %my_hash;

The variable $size will now contain the number of keys in your Perl hash, which is the size of the hash, i.e., the total number of key/value pairs in the hash.

Perl hash size - a complete example

As a more thorough Perl hash size answer, let's build a complete Perl script. First, we define a Perl hash named %prices, like this:

# create our perl hash
$prices{"pizza"} = 12.00;
$prices{"coke"} = 1.25;
$prices{"sandwich"} = 3.00;

Now we can get the size of our Perl hash, like this:

$size = keys %prices;

Putting this all together in a Perl script, and printing the Perl hash size at the end of the script, we have this:

#!/usr/bin/perl

# a "perl hash size" demo script
# devdaily.com

# create our perl hash
$prices{'pizza'} = 12.00;
$prices{'coke'} = 1.25;
$prices{'sandwich'} = 3.00;

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

# print the hash size
print "The hash contains $size elements.\n";

which gives us this output:

The hash contains 3 elements.

More Perl hash tutorials

I hope you found this Perl hash size tutorial helpful. We have many more Perl hash tutorials on this site, including the following:

Getting started Perl hash tutorials:

More advanced Perl hash tutorials:

The hash in Perl - hash sorting tutorials: