Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

hash size

by Galen (Beadle)
on Apr 18, 2001 at 20:10 UTC ( [id://73550]=perlquestion: print w/replies, xml ) Need Help??

Galen has asked for the wisdom of the Perl Monks concerning the following question:

Is there a method for directly retrieving the size of a hash, or must I use an array?
%somehash = ( key1 => "value1", key2 => "value2", key3 => "value3, key4 => "value4", ); @keys = keys %somehash; $size = @keys; print "This hash holds $size key-value pairs\n";

Replies are listed 'Best First'.
Re: hash size
by davorg (Chancellor) on Apr 18, 2001 at 20:14 UTC
Re: hash size
by arturo (Vicar) on Apr 18, 2001 at 20:17 UTC

    "size of a hash" isn't really well defined. You can get the number of keys, or the number of values pretty easily. (does a key w/o a defined value count? It might not for some purposes). You can cut down the keystrokes on your method with something like the following:

    print "This hash holds ". scalar keys %somehash . " keys\n";

    HTH

    perl -e 'print "How sweet does a rose smell? "; chomp ($n = <STDIN>); +$rose = "smells sweet to degree $n";*other_name = *rose;print "$other +_name\n"'
Re: hash size
by larsen (Parson) on Apr 18, 2001 at 20:54 UTC
    Another point from perldata. It could be useful for a certain definition of size :)...
    If you evaluate a hash in a scalar context, it returns a value which is true if and only if the hash contains any key/value pairs. (If there are any key/value pairs, the value returned is a string consisting of the number of used buckets and the number of allocated buckets, separated by a slash. This is pretty much useful only to find out whether Perl's (compiled in) hashing algorithm is performing poorly on your data set. For example, you stick 10,000 things in a hash, but evaluating %HASH in scalar context reveals "1/16", which means only one out of sixteen buckets has been touched, and presumably contains all 10,000 of your items. This isn't supposed to happen.)
Re: hash size
by zigster (Hermit) on Apr 18, 2001 at 20:18 UTC
    Not really AFAIC. You can shorten things sumwhat by calling keys in scalar context:
    %somehash = ( key1 => "value1", key2 => "value2", key3 => "value3, key4 => "value4", ); $size = keys %somehash; print "This hash holds $size key-value pairs\n";

    --

    Zigster

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://73550]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (4)
As of 2024-03-19 11:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found