Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
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
Replies are listed 'Best First'.
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 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

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;

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 making s'mores by the fire in the courtyard of the Monastery: (5)
As of 2015-08-01 02:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (285 votes), past polls