Gossamer Forum
Home : Products : Gossamer Links : Discussions :

How to count # of elements in a hash

Quote Reply
How to count # of elements in a hash
Hi there,

Does anyone know how to count the number of keys in a hash?
You can use this to get the number of elements in an array
$count=$#{$array};

but I've got a grouping hash and for the life of me can't figure out how to find out how many keys there are without scanning it twice. once to count and the second time to do what I need to do based on the count, and none of my books mention it. I need a better book.

Thanks for replying to such an inane question.

peace.

Kyle
Quote Reply
Re: [klangan] How to count # of elements in a hash In reply to
>>
You can use this to get the number of elements in an array
$count=$#{$array};
<<

For an array I use:

my $count = scalar @array;

For a hash you can do the same:

my $count = scalar keys %hash;
Quote Reply
Re: [RedRum] How to count # of elements in a hash In reply to
Smilethank you thank you thank you.Smile
Quote Reply
Re: [klangan] How to count # of elements in a hash In reply to
Did it work or was that a hopeful thankyou?
Quote Reply
Re: [RedRum] How to count # of elements in a hash In reply to
Oh no, it worked perfectly - it even gave me the right count I've been after for the past 3 days!

thanks again.

peace.

Kyle
Quote Reply
Re: [klangan] How to count # of elements in a hash In reply to
Blush