How to find the number of pairs of elements in a Perl hash

Task. In the program in the programming language Perl is the hash. You need to figure out how many pairs values in it.

For example, this hash is necessary to set to 1:

my %h = (
    a => 'AAA',
);

And for such a hash, you need to get the value 3:

my %h = (
    a => 'AAA',
    b => 'BBB',
    c => 'CCC',
);

The decision

The standard solution to this problem is to first get all the keys of the hash by using keys, and then to count the number of keys by using scalar context. Here is the script in full:

▶ Run
#!/usr/bin/perl

my %h = (
    a => 'AAA',
    b => 'BBB',
);

my $number = scalar keys %h;

print $number;

The script will display the number 2. scalar keys %h is the same as scalar(keys(%h)).

This solution works on all versions of Perl. And often this decision is best.

The decision in new versions of Perl

Perl 5.26 the number of pairs of values in the hash can be obtained simply by using scalar %h.

And this has resulted in consistency between how to get the number of elements in the array scalar @arr and as to the number of pairs of values in the hash scalar %h. It is a pity that this behavior was not created initially.

If you use scalar %h in Perl earlier than 5.26, the result of this operation is a strange fraction of the species 1/8. (an explanation of what this fraction means). Because of this a more reliable option for finding the number of pairs in the hash is still the option scalar keys %h.

Related topics

Other articles

Comments