What characters are valid in hash keys?

For each question: what are the characters that can be used in the hash keys or, if they are shorter, which ones cannot be used?

Also, are there any problems using long hash keys (e.g. full path names)?

+7
syntax perl
source share
4 answers

See How hash really works for a discussion of this topic. In short, as long as you specify a key (not interpolating q {}), you can use any characters you want.

Regarding Danaโ€™s answer, no, it wonโ€™t take longer until the longer keys are agreed: it will take infinitely longer to hash the key, but thatโ€™s it.

For reference, this is a hash 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 
+19
source share

You can use any character valid in a string. Length is also not a problem. Perl can do anything :)

+6
source share

Another problem that cannot be raised is that you can use any valid string as a hash key. If you try to use anything other than a string, it will be automatically stiff, which means that, for example,

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

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

+6
source share

You can use any character in a hash key --- a hash key is just a string. But for some characters you need to quote a line. If in doubt, simply put quotation marks around the key.

 $hash{simplekey} # fine $hash{/var/log/auth.log} # syntax error --- can't use '/' directly $hash{"/var/log/auth.log"} # quoted string, so can use any character my $key = "/var/log/auth.log"; $hash{$key} # variable used, which can contain any character 

There is no particular problem with using long keys that you do not already have with long lines.

+5
source share

All Articles