开发者

Why do I see my Perl hash as a fraction, like '28/64'?

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

$myshash{"/de开发者_高级运维v/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?


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.


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.


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.


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> 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜