Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

find a number of keys in a hash

by perlthirst (Scribe)
on Jan 16, 2009 at 14:20 UTC ( #736837=perlquestion: print w/ replies, xml ) Need Help??
perlthirst has asked for the wisdom of the Perl Monks concerning the following question:

hi,

how to find a number of keys in a hash with out declaring temporary array?

I am able to get number of keys in a hash, by using the following method

use strict; use warnings; my %data= ( 'a' => 'b', 'c' => 'd', 'e' => 'f' ); my @keylen = keys %data; print $#keylen;

But here I have used array named as keylen and then i got the total number of keys.

Is it possible to take in a step. Kindly advice.

Comment on find a number of keys in a hash
Download Code
Re: find a number of keys in a hash
by setebos (Beadle) on Jan 16, 2009 at 14:25 UTC
    scalar(keys(%hash_name))
Re: find a number of keys in a hash
by jwkrahn (Monsignor) on Jan 16, 2009 at 14:25 UTC

    Using keys in scalar context will return the number of keys in the hash:

    my $keylen = keys %data; print $keylen;
Re: find a number of keys in a hash
by Fletch (Chancellor) on Jan 16, 2009 at 14:26 UTC

    Actually you got 1 less than the number of keys because arrays are zero based, but that's a different problem. If you read the keys documentation the second sentence explains that calling it in scalar context returns the number of keys: my $num_keys = keys %data.

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

      Or the last index of the array (if you change $[)

      --MidLifeXis

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (9)
As of 2014-12-20 17:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (97 votes), past polls