in reply to Hash key string restrictions?
That is most definitely a unique question!
As ikegami and Joost have said, any string will work.
Having said that, though, there is one exception: an empty string will NOT work, but if you should try to use one, you'll get a syntax error (even in the absence of strict and warnings). (Update: as Limbic~Region correctly advises, even an empty string is legal. My test case was apparently in error.)
I thought any string would be legal, but I wanted to be certain, so I wrote the following test program for fun:
# Strict use strict; use warnings; # Libraries; use Data::Dumper; # Main program $| = 1; my $phash = { }; my $parray = [ ]; my $ndiff = 0; # Save all single characters and character pairs as hash keys for (my $i = 0; $i < 256; $i++) { save_to_hash_and_array($i); for (my $j = 0; $j < 256; $j++) { save_to_hash_and_array($i, $j); } } # Test all single characters for (my $i = 0; $i < 256; $i++) { my $is_same = hash_matches_array($i)? 1: 0; $is_same or $ndiff++; printf "%s", $is_same? ".": "@"; } print "\n\n"; # Test all character pairs for (my $i = 0; $i < 256; $i++) { for (my $j = 0; $j < 256; $j++) { my $is_same = hash_matches_array($i, $j)? 1: 0; $is_same or $ndiff++; printf "%s", $is_same? ".": "@"; } } print "\n\n"; print "Number of mismatches = $ndiff\n"; # Uncomment out this line to see a lot of strange character print "Type [RETURN] to see a dump of the hash ... "; <STDIN>; print Dumper($phash), "\n"; sub save_to_hash_and_array { my ($idx0, $idx1) = @_; my $key = chr($idx0); defined($idx1) and $key .= chr($idx1); my $value = sprintf "(%s:%s)", $idx0, ($idx1 || "blank"); $phash->{$key} = $value; $parray->[$idx0 + 256*($idx1||0)] = $value; } sub hash_matches_array { my ($idx0, $idx1) = @_; my $key = chr($idx0); defined($idx1) and $key .= chr($idx1); my $hval = $phash->{$key}; my $aval = $parray->[$idx0 + 256*($idx1||0)]; return ($hval eq $aval)? 1: 0; }
Sure enough, it confirmed what I suspected. No difference between the value assigned to each key and the result pulled out of the hash later (as compared against the same value saved in an array), for all possible single characters, and all possible character pairs for good measure.
But I'm still very curious -- how on earth did such a question occur to you?!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Hash key string restrictions?
by Limbic~Region (Chancellor) on Feb 10, 2007 at 00:30 UTC |