tags:

views:

272

answers:

4

Hi. I'm trying to set key name in a hash to a string containig "/" symbols, for instance

$myshash{"/dev/shm"} = "shared memory";

But what I get is something like '28/64' and so on when viewing with Data::Dumper. How can I use these special chars in hash key names?

+3  A: 

Your hash is working fine... it's just that you're using Data::Dumper incorrectly.

If you do:

print $myshash{"/dev/shm"};

you will see that it is working.

JoelFan
+26  A: 

The 28/64 is coming from viewing the hash as a scalar, and is a representation of how many buckets are used (and the total number of buckets). Dump it as a hash instead of a scalar, and you should see the correct data -- there's nothing wrong with what you have done.

This works fine for me:

use Data::Dumper;

my %hash;
$hash{"/dev/shm"} = "shared memory";

print Dumper(\%hash);

and outputs:

$VAR1 = {
          '/dev/shm' => 'shared memory'
        };

To clarify and answer your root question, you're not using special characters in a hash. Since most languages internally hash a string to an integer (still learning Perl, but this is how Python works), you could put runic glyphs from the writings of the High Elves in there if you want, and key creation would work fine. The hash function doesn't care.

Jed Smith
White it's true the language internally hashes the string to an integer, that doesn't mean the original string doesn't matter. It's possible for several different strings to hash to the same integer (a "hash collision") so the original "key" strings still needed to be stored (and looked up) in the hash structure somewhere
JoelFan
+3  A: 

Looks like it works for me:

$ perl -de0

Loading DB routines from perl5db.pl version 1.3
Editor support available.

Enter h or `h h' for help, or `man perldebug' for more help.

main::(-e:1):   0
  DB<1> $myshash{"/dev/shm"} = "shared memory";

  DB<3> x %myshash
0  '/dev/shm'
1  'shared memory'
  DB<4>
Jim Garrison
+15  A: 

Remember to give Data::Dumper references to what you want to dump:

use Data::Dumper;
my %myshash;
$myshash{"/dev/shm"} = "shared memory";
print Dumper \%myshash;

Output:

C:\Temp> t.pl
$VAR1 = {
          '/dev/shm' => 'shared memory'
        };

See also perldoc perldata:

If you evaluate a hash in scalar context, it returns false if the hash is empty. If there are any key/value pairs, it returns true; more precisely, the value returned is a string consisting of the number of used buckets and the number of allocated buckets, separated by a slash. This is pretty much useful only to find out whether Perl's internal hashing algorithm is performing poorly on your data set.

Sinan Ünür
My fault. Forgot about \%Thanks alot!
Dmytro Leonenko