tags:

views:

73

answers:

2

Suppose I have a file with n words. As I read each word in the file, I will store it in hash (in Perl). When I go back and look up for the word in the hash, what is the time complexity of looking up a string(word) in a hash?

For example:

my %seen = ();
@arr=("one","two","three");
foreach $item (@arr){
    if($seen{$item}) {//do something}
}

In this program, I am looking up for an item in the hash. What is time complexity of looking up for a string in a hash?

Also, could any elaborate on how hash is implemented in Perl? (internally something happens in hash? or is it just an associative array)

+10  A: 

Perl hashes provide constant-time lookups. They are implemented as true hash tables (with automatic retuning as necessary), not associative arrays.

friedo
Is this irrespective of whatever the key is? Key can be a string also..right?
Chandu
@sekhar, the key can _only_ be a string. Numbers and references get converted to strings when used as hash keys.
cjm
@friedo, Perl hashes _are_ associative arrays. An [associative array](http://en.wikipedia.org/wiki/Associative_array) is an abstract data type; hash tables are one way to implement it.
cjm
+3  A: 

If you want to see how Perl implements hashes, work your way through the source in hv.c and hv.h. If you want just the overview, you might try perlguts. However, as friedo says, the time to look up any key is the same time to look up any other key. It's a real hash.

You might also want to see Jon Bentley's essays on hashes in Programming Pearls (not a Perl book).

brian d foy