Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the number of keys in a hash in Perl?

Tags:

hash

perl

How do I find the number of keys in a hash, like using $# for arrays?

like image 894
joe Avatar asked Jul 10 '09 11:07

joe


People also ask

How will you get the size of a hash?

But a good general “rule of thumb” is: The hash table should be an array with length about 1.3 times the maximum number of keys that will actually be in the table, and. Size of hash table array should be a prime number.

What is key in hash?

Answer: The hashing key is the raw data in which to be hashed. The hashing algorithm is the algorithm which performs a function to convert the hash key to the hash value. the hash value is what is produced as a result of the hash key being passed into the hashing algorithm.

How do I check if a Perl hash is empty?

From perldoc perldata: If you evaluate a hash in scalar context, it returns false if the hash is empty. If there are any key/value pairs, it returns true; more precisely, the value returned is a string consisting of the number of used buckets and the number of allocated buckets, separated by a slash.

What are keys Perl?

keys() function in Perl returns all the keys of the HASH as a list. Order of elements in the List need not to be same always, but, it matches to the order returned by values and each function. Syntax: keys(HASH) Parameter: HASH: Hash whose keys are to be printed.


2 Answers

scalar keys %hash 

or just

keys %hash 

if you're already in a scalar context, e.g. my $hash_count = keys %hash  or  print 'bighash' if keys %hash > 1000.

Incidentally, $#array doesn't find the number of elements, it finds the last index. scalar @array finds the number of elements.

like image 57
chaos Avatar answered Sep 21 '22 03:09

chaos


we can use like this too

my $keys = keys(%r) ; print "keys = $keys" ;   0+(keys %r)  
like image 39
joe Avatar answered Sep 22 '22 03:09

joe