打印哈希

时间:2013-07-05 06:52:10

标签: perl

目的 我正在制作哈希并将其打印以计算大型文档中单词的频率。 在结果文件中,我收到了一些意外的条目。

问题 散列有一个额外的输出HASH(0x55b0ac)

我在排查方面的进展

将代码分解成更小的部分并单独测试每个组件后,我发现问题在于打印哈希。我在这里写了一小段代码,它们复制了同样的问题。

代码:

my %testhash = {};
$teststr = "using this for testing this that";

foreach $word (split(' ', lc $teststr)) {
$testhash{$word}++;
}

foreach $word (sort keys %testhash) {
    print $word."\t".$testhash{$word}."\n";
}

预期输出

for     1
testing 1
that    1
this    2
using   1

获得的输出

HASH(0x55b0ac)
for     1
testing 1
that    1
this    2
using   1

注意 我知道我的问题可以通过使用if条件解决,如果$ testhash {$ word}为NULL则不打印行。我的问题是了解这次意外进入的原因。是否与声明哈希或打印它有关?

编辑: 每次重新运行代码时,数字0x55b0ac都会改变

3 个答案:

答案 0 :(得分:8)

你的问题是第一行。这有效:

my %testhash;
my $teststr = "using this for testing this that";

foreach my $word (split(' ', lc $teststr)) {
    $testhash{$word}++;
}

foreach my $word (sort keys %testhash) {
    print $word."\t".$testhash{$word}."\n";
}

答案 1 :(得分:2)

 use Data::Dumper;
 # your other code here
 print Dumper(\%testhash);

我通常做以上... Data :: Dumper是一个非常有用的模块

答案 2 :(得分:0)

我想是这样的..

my %testhash;
my $teststr = "using this for testing this that";
$testhash{$_}++ for split /\s+/, lc $teststr;
print $_ . "\t" . $testhash{$_} . "\n", for sort keys %testhash;
相关问题