Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What characters are valid in hash keys?

Tags:

syntax

perl

As per subject: what are the characters that can be used in hash keys or, if it's shorter, which ones can't be used?

Also, are there any problems in using long hash keys (like full path names)?

like image 649
Matteo Riva Avatar asked Dec 15 '09 10:12

Matteo Riva


People also ask

Does a hash have letters in it?

So it is possible for the usual string representation of a hash to contain only letters or only decimal digits. Definitely valid and possible. Just like it's possible for a decimal number to contain only odd digits.

Where is hash key used?

Number sign, also known as the number, pound or hash key, a key on a telephone keypad. For its use in data structure, database and cryptographic applications, see hash function or unique key.


2 Answers

See How Hashes Really Work for a discussion on this topic. In short, as long as you quote the key (non-interpolating q{}), you can use whatever characters you want.

Regarding Dana's answer, no, it won't take longer for longer keys to get matched: it will take infinitesimally longer to hash the key, but that's all.

For reference, this is the hashing function in Perl 5.10.0:

#define PERL_HASH(hash,str,len)
 STMT_START {
    register const char * const s_PeRlHaSh_tmp = str;
    register const unsigned char *s_PeRlHaSh = (const unsigned char *)s_PeRlHaSh_tmp;
    register I32 i_PeRlHaSh = len;
    register U32 hash_PeRlHaSh = PERL_HASH_SEED;
    while (i_PeRlHaSh--) {
        hash_PeRlHaSh += *s_PeRlHaSh++;
        hash_PeRlHaSh += (hash_PeRlHaSh << 10);
        hash_PeRlHaSh ^= (hash_PeRlHaSh >> 6);
    }
    hash_PeRlHaSh += (hash_PeRlHaSh << 3);
    hash_PeRlHaSh ^= (hash_PeRlHaSh >> 11);
    (hash) = (hash_PeRlHaSh + (hash_PeRlHaSh << 15));
} STMT_END
like image 184
Pedro Silva Avatar answered Nov 03 '22 03:11

Pedro Silva


One point not brought up yet is that you can use any valid string as a hash key. If you try to use something other than a string, it will be automatically stringified, which means that, e.g.,

my $ref = [];
$hash{$ref} = 'foo';

will use the string "ARRAY(0xdeadbeef)" (or whatever address) as the hash key, not the actual array reference.

like image 43
Dave Sherohman Avatar answered Nov 03 '22 03:11

Dave Sherohman