Getting Hash Size in Perl

PERLServer Side ProgrammingProgramming Scripts

You can get the size - that is, the number of elements from a hash in Perl by using the scalar context on either keys or values. Simply saying first you have to get an array of either the keys or values and then you can get the size of the array as follows −

Example

 Live Demo

#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
@keys = keys %data;
$size = @keys;
print "1 - Hash size: is $size\n";
@values = values %data;
$size = @values;
print "2 - Hash size: is $size\n";

Output

This will produce the following result −

1 - Hash size: is 3
2 - Hash size: is 3
raja
Published on 29-Nov-2019 05:56:53
Advertisements