Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

getting the number of hashes

by damian (Beadle)
on Jul 21, 2000 at 07:32 UTC ( #23533=perlquestion: print w/replies, xml ) Need Help??

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

hi monks, how will i know the total number of hashes i have. thanks

Replies are listed 'Best First'.
Re: getting the number of hashes
by turnstep (Parson) on Jul 21, 2000 at 17:17 UTC

    I suspect they may be asking for the number of hash elements in a particular hash. If so, perlfaq4 comes to the rescue:

    How can I know how many entries are in a hash?

    If you mean how many keys, then all you have to do is take the scalar sense of the keys() function:

    $num_keys = scalar keys %hash;

    In void context, the keys() function just resets the iterator, which is faster for tied hashes than would be iterating through the whole hash, one key-value pair at a time.

    In other words, it's better to use the above than to use something like these:

    $number = grep(//, keys %hash); for (keys %hash) { $number++; }

    However, grep is a good solution if you want something more specific, for example:

    ## Find the number of elements that are defined: $number = grep(defined $hash{$_}, keys %hash); ## Find the number of elements that are "true": $number = grep($_, values %hash); ## Find the number of elements where the key equals the value: $number = grep($_ eq $hash{$_}, keys %hash);
Re: getting the number of hashes
by Russ (Deacon) on Jul 21, 2000 at 07:44 UTC
    Well, you could search the symbol table...

    But, the better question is to you: why would you want to know? Perhaps we can find a better way to do what you're doing.

    Brainbench 'Most Valuable Professional' for Perl

Re: getting the number of hashes
by young perlhopper (Scribe) on Jul 21, 2000 at 17:20 UTC
    You could store references to all your hashes in a list,
    @array = ( \%hash1, \%hash2, \%hash3 );

    and then take the size of the array by scalar( @array );
    If however, you mean finding the number of keys in a given hash, do this:

    $var = keys %hash2;
    $var now contains the number of key value pairs in the hash.


Log In?

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

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (2)
As of 2022-09-25 01:22 GMT
Find Nodes?
    Voting Booth?
    I prefer my indexes to start at:

    Results (116 votes). Check out past polls.