Reg hashes

S

sunil

Hi!
I have two simple questions. I am using PERL version 5.005 and
hence I should be able to preallocate hashes using something like:
keys(%myhash)=50000. But is there any way to verify this? When I do
scalar(keys%myhash), it shows 0.
Second question is about collisions when using hashes. I am assuming
that perl takes care of collisions so that if two keys happen to map
to same bucket, the new element will be placed either in linked list
or at next available slot in hash bucket array. But do hash functions
take care of this? For example if I call exists ($myhash{"hello"}) and
lets assume hash has key called "hallo" but not "hello". If both keys
"hallo" and "hello" map to same hash index,does
exists($myhash("hello")) return 0 as we expect?
Thanks,
Sunil.
 
B

Brian McCauley

I have two simple questions. I am using PERL version 5.005
and hence I should...

... upgrade.
... be able to preallocate hashes using something like:
keys(%myhash)=50000. But is there any way to verify this? When I do
scalar(keys%myhash), it shows 0.

That is correct. scalar(keys(%myhash)) returns the number of keys not the
number of buckets.

scalar(%myhash) will return the bucket usage - but not if the hash is
empty. If the hash is empty then it returns '0' so that it is false
in a boolean context.

keys(%myhash) = 50000;
$myhash{dummy} = undef;
print scalar %myhash; # prints "1/65536"

This shows that %myhash is using 1/65536 buckets. (The number of
buckets is always a power of 2 AFAIK).
Second question is about collisions when using hashes. I am assuming
that perl takes care of collisions so that if two keys happen to map
to same bucket, the new element will be placed either in linked list
or at next available slot in hash bucket array.

Yes, of course.
But do hash functions take care of this?

Yes, of course.
For example if I call exists ($myhash{"hello"}) and
lets assume hash has key called "hallo" but not "hello". If both keys
"hallo" and "hello" map to same hash index,does
exists($myhash("hello")) return 0 as we expect?

Yes, of course.

Just think Perl "hashes" as un-ordered associative arrays - don't
think about how they are implemented unless you really need to. It
is, I think, widely accepted that the choice of name "hash" for Perl's
associative array data type was bad because it causes people to think
about the implementation when really they shouldn't.

--
\\ ( )
. _\\__[oo
.__/ \\ /\@
. l___\\
# ll l\\
###LL LL\\
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top